开发者

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.esc开发者_运维知识库ape('+'))         # => ''

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


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.


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!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜