简体   繁体   English

在Ruby中的正则表达式中转义\\

[英]Escaping \ in regular expressions in Ruby

I was parsing a file and some lines of the file ended with "\\". 我正在解析一个文件,文件的某些行以“\\”结尾。 I wanted to use gsub to find and replace it. 我想用gsub来查找和替换它。 I tried '\\' and /\\/ and neither one correctly matched "\\". 我试过'\\'和/ \\ /,两者都没有正确匹配“\\”。

I ended up getting around it by using a combination of chop and strip but it left me thinking how would I do this if I ever need to again? 我最后通过使用剁和条带的组合绕过它,但它让我想到如果我再次需要我将如何做到这一点?

You need to escape the escape sign as well. 你也需要逃脱逃生标志。 So this should work: 所以这应该工作:

/\\/

Passing a string to gsub that will then be compiled to a regex: 将字符串传递给gsub,然后将其编译为正则表达式:

"abc\def".gsub("\\", "")
=> "abcdef"

Or just providing the regex directly: 或者直接提供正则表达式:

"abc\def".gsub(/\\/, "")
=> "abcdef"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM