John Doe John Doe - 1 year ago 63
Ruby Question

Unable to highlight quoted string using regex in ruby

The regex pattern works when I try it in

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

I am expecting the output to be:

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

But instead I am getting:

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

Answer Source

Don't you think you are printing and capturing wrong. It should be

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download