gpt4 book ai didi

ruby - 如何使用正则表达式转换 Markdown 样式的链接?

转载 作者:数据小太阳 更新时间:2023-10-29 06:35:13 26 4
gpt4 key购买 nike

我正在尝试编写一个正则表达式来替换 markdown 样式的链接,但它似乎不起作用。这是我目前所拥有的:

# ruby code:
text = "[link me up](http://www.example.com)"
text.gsub!(%r{\[(\+)\]\((\+)\)}x, %{<a target="_blank" href="\\1">\\2</a>})

我做错了什么?

最佳答案

irb(main):001:0> text = "[link me up](http://www.example.com)"
irb(main):002:0> text.gsub /\[([^\]]+)\]\(([^)]+)\)/, '<a href="\2">\1</a>'
#=> "<a href=\"http://www.example.com\">link me up</a>"

我们可以为 Ruby 的正则表达式使用 extended 选项,让它看起来不像一只猫跳到键盘上:

def linkup( str )
str.gsub %r{
\[ # Literal opening bracket
( # Capture what we find in here
[^\]]+ # One or more characters other than close bracket
) # Stop capturing
\] # Literal closing bracket
\( # Literal opening parenthesis
( # Capture what we find in here
[^)]+ # One or more characters other than close parenthesis
) # Stop capturing
\) # Literal closing parenthesis
}x, '<a href="\2">\1</a>'
end

text = "[link me up](http://www.example.com)"
puts linkup(text)
#=> <a href="http://www.example.com">link me up</a>

请注意,对于其中包含右括号的 URL,上述操作将失败,例如

linkup "[O](http://msdn.microsoft.com/en-us/library/ms533050(v=vs.85).aspx)"
# <a href="http://msdn.microsoft.com/en-us/library/ms533050(v=vs.85">O</a>.aspx)

如果这对您很重要,您可以将 [^)]+ 替换为 \S+(?=\)) 这意味着 “找到尽可能多的尽可能使用非空白字符,但要确保之后有 )"


要回答您的问题“我做错了什么”,您的正则表达式是这样说的:

%r{
\[ # Literal opening bracket (good)
( # Start capturing (good)
\+ # A literal plus character (OOPS)
) # Stop capturing (good)
\] # Literal closing bracket (good)
\( # Literal opening paren (good)
( # Start capturing (good)
\+ # A literal plus character (OOPS)
) # Stop capturing (good)
\) # Literal closing paren (good)
}x

关于ruby - 如何使用正则表达式转换 Markdown 样式的链接?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9268407/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com