From: Robert Klemme Date: 2009-05-11T15:40:15+09:00 Subject: Re: gsub pattern substitution and ${...} On 11.05.2009 02:18, Sarah Allen wrote: > 7stud -- wrote: >> If you need to use double quoted strings, then you need to literally >> have \1 in your string, which requires the use of additional backslashes >> to escape the \ in "\1". So try "\\1". With ruby if one backslash is >> not enough, keep adding more backslashes until whatever you are trying >> accomplish works! > > Eureka! > >>> s.gsub(/href=(['"])([^']*)/, "href=\\1#{URI.escape($2)}\\3") > => "" > > Thanks so much for your help. That does not work as 7stud did not mention the most important point: even with proper escaping this won't work as the string interpolation takes place *before* gsub is invoked and hence URI.escape will insert something but not the matched portion. In your tests it has probably worked because $2 was properly set from the previous match. In this case the block form of gsub is needed: irb(main):007:0> s = "" => "" irb(main):008:0> s.gsub(/href=(["'])([^'"]+)\1/) { "href=#$1#{URI.escape($2)}#$1" } => "" irb(main):009:0> s = "two\"/>" => "two\"/>" irb(main):010:0> s.gsub(/href=(["'])([^'"]+)\1/) { "href=#$1#{URI.escape($2)}#$1" } => "" And if quotes differ with my regexp no replacement takes place: irb(main):011:0> s = "two'/>" => "two'/>" irb(main):012:0> s.gsub(/href=(["'])([^'"]+)\1/) { "href=#$1#{URI.escape($2)}#$1" } => "two'/>" Whether this is something you want or not depends on you but AFAIK mixing quote types is not allowed here so we probably rather not want to do the replacement in that case. Note that my regexp has another weakness: the quote character not used to quote the URI should be allowed as part of the URI. I did not want to complicate things too much but if you want to deal with this the regular expression must be made a bit more complex. Kind regards robert -- remember.guy do |as, often| as.you_can - without end http://blog.rubybestpractices.com/