John Doe John Doe - 7 months ago 6
Ruby Question

Unable to highlight quoted string using regex in ruby

The regex pattern works when I try it in regexr.com

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

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

Comments