And*_*rew 16 ruby regex markdown
我正在尝试编写一个替换markdown样式链接的正则表达式,但它似乎不起作用.这是我到目前为止:
# ruby code:
text = "[link me up](http://www.example.com)"
text.gsub!(%r{\[(\+)\]\((\+)\)}x, %{<a target="_blank" href="\\1">\\2</a>})
Run Code Online (Sandbox Code Playgroud)
我究竟做错了什么?
Phr*_*ogz 39
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>"
Run Code Online (Sandbox Code Playgroud)
我们可以使用x
Ruby的正则表达式的e tended选项使它看起来不像是跳到键盘上的猫:
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>
Run Code Online (Sandbox Code Playgroud)
请注意,对于其中包含右括号的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)
Run Code Online (Sandbox Code Playgroud)
如果这对你很重要,你替换[^)]+
用\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
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
4115 次 |
最近记录: |