如何使用正则表达式转换Markdown风格的链接?

时间:2012-02-13 21:36:05

标签: 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>})

我做错了什么?

1 个答案:

答案 0 :(得分:38)

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的正则表达式的e x趋势选项,使它看起来不像是跳到键盘上的猫:

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>

请注意,对于其中包含右括号的网址,上述内容将失败,例如

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+(?=\)),这意味着“找到尽可能多的非空白字符,但请确保存在) 1}}之后“


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

%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