Vitor Baptista
Vitor Baptista

Reputation: 2096

Why I can't substitute with '\\+' inside a string with gsub?

Try the following code:

s = '#value#'
puts s.gsub('#value#', Regexp.escape('*'))         # => '\*'
puts s.gsub('#value#', Regexp.escape('+'))         # => ''

Wtf? It looks like the char '\+' (returned by Regexp.escape) is completely ignored by gsub. How to fix this?

Upvotes: 3

Views: 151

Answers (2)

miorel
miorel

Reputation: 1833

It's because of the interpolation of special variables. \+ will be replaced with "the text matched by the highest-numbered capturing group that actually participated in the match" (See the Special Variables section on http://www.regular-expressions.info/ruby.html)

The block syntax is in fact a fix for this, well done.

Upvotes: 3

Vitor Baptista
Vitor Baptista

Reputation: 2096

xsdg of #ruby worked this out

Looks like that gsub's replacement is parsed, so the + is lost somewhere in the process. A workaround is using gsub's block syntax. This way:

s = '#value#'
puts s.gsub('#value#') { |v| Regexp.escape('+') }          # => '+'

Works as expected :)

Thanks, xsdg!

Upvotes: 1

Related Questions