无法在ruby中使用正则表达式突出显示引用的字符串

时间:2016-04-17 07:14:01

标签: ruby regex

当我在regexr.com中试用时,正则表达式模式有效。

pattern = %r{(["'])(?:\\\1|[^\1])*?\1}
string = %Q(var msg = 'hello' + 'world')
string.gsub(pattern, '<span>\1</span>')

我期待输出为:

"var msg = <span>'hello'</span> + <span>'world'</span>"

但相反,我得到了:

# => "var msg = <span>'</span> + <span>'</span>"

2 个答案:

答案 0 :(得分:1)

你不认为你正在打印和捕获错误。它应该是

pattern = %r{(["'])(\\\1|[^\1]*?)\1}
                      # ^^
                      # ||
   #(This will capture the string hello etc. which are after quotes) 
string = %Q(var msg = 'hello' + 'world')
string.gsub(pattern, '<span>\1\2\1</span>')

<强> Ideone Demo

答案 1 :(得分:0)

我认为使用没有捕获组的正则表达式会更清楚。

r = /
    (?:'.+?') # match one or more of any character, lazily, surrounded by
              # single quotes, in a non-capture group
    |         # or
    (?:".+?") # match one or more of any character, lazily, surrounded by
              # double quotes, in a non-capture group
    /x        # free-spacing regex definition mode

你通常会看到写的

r = /(?:'.+?')|(?:".+?")/

然后

"var msg = 'hello' + 'world'".gsub(r) { |s| "<span>%s</span>" % s }
  #=> "var msg = <span>'hello'</span> + <span>'world'</span>" 
"var msg = \"hello\" + \"world\"".gsub(r) { |s| "<span>#{s}</span>" }
  #=> "var msg = <span>\"hello\"</span> + <span>\"world\"</span>" 
"var msg = 'It is my' + 'friend Bubba'".gsub(r) { |s| "<span>"+s+"</span>" }
  #=> "var msg = <span>'It is my'</span> + <span>'friend Bubba'</span>"