开发者

How to replace regex string with '\'

开发者 https://www.devze.com 2023-03-20 03:59 出处:网络
I want to include the \'\\\' character in the regex replacement. For example: E{bla}-> \\bla The statement I use (in ruby) is

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

精彩评论

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