开发者

How to replace regex string with '\'

I want to include the '\' character in the regex replacement. For example:

E{bla}      -> \bla

The statement I use (in ruby) is

text.gsub!(/\\E{(\w*)}/,开发者_开发问答 '\\\1')

but I get

E{bla}      -> \1

instead. How do I get what I want?


You'll need 6 backslashes like this:

text.gsub!(/\\E{(\w*)}/, '\\\\\1')

The \\\\\\1 gets passed to gsub as \\\1 (the 1st, 3rd and 5th backslashes each escape the following backslash). This is interpreted by the regexp engine as \ followed by \1 (the first backslash escapes the second backslash)

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜