And*_*ume 8 ruby string replace
我正在尝试在Ruby中做一个简单的字符串sub.
sub()的第二个参数是一小段缩小的JavaScript,其中包含正则表达式.此字符串中正则表达式中的后向引用似乎影响了sub的结果,因为替换的字符串(即第一个参数)出现在输出字符串中.
例:
input = "string <!--tooreplace--> is here"
output = input.sub("<!--tooreplace-->", "\&")
Run Code Online (Sandbox Code Playgroud)
我希望输出为:
"string \& is here"
Run Code Online (Sandbox Code Playgroud)
不:
"string & is here"
Run Code Online (Sandbox Code Playgroud)
或者如果逃避正则表达式
"string <!--tooreplace--> is here"
Run Code Online (Sandbox Code Playgroud)
基本上,我想要一些方法来做一个没有正则表达式后果的字符串sub - 只是一个简单的字符串替换.
为避免弄清楚如何逃避替换字符串,请使用Regex.escape.当替换件很复杂时,它很方便,或者处理它是一种不必要的痛苦.String上的一个小帮手也很好.
input.sub("<!--toreplace-->", Regexp.escape('\&'))
Run Code Online (Sandbox Code Playgroud)
使用单引号并转义反斜杠:
output = input.sub("<!--tooreplace-->", '\\\&') #=> "string \\& is here"
Run Code Online (Sandbox Code Playgroud)