为什么不使用“gsub”删除管道在鲁比?
我想从 notes
中删除从 example_header
开始的所有内容。我尝试这样做:
example_header = <<-EXAMPLE
-----------------
---| Example |---
-----------------
EXAMPLE
notes = <<-HTML
Hello World
#{example_header}
Example Here
HTML
puts notes.gsub(Regexp.new(example_header + ".*", Regexp::MULTILINE), "")
但输出是:
Hello World
||
为什么 ||
没有被删除?
I would like to delete from notes
everything starting from the example_header
. I tried to do:
example_header = <<-EXAMPLE
-----------------
---| Example |---
-----------------
EXAMPLE
notes = <<-HTML
Hello World
#{example_header}
Example Here
HTML
puts notes.gsub(Regexp.new(example_header + ".*", Regexp::MULTILINE), "")
but the output is:
Hello World
||
Why ||
isn't deleted?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
正则表达式中的管道被解释为交替运算符。您的正则表达式将替换以下三个字符串:
您可以使用
Regexp.escape
在正则表达式中使用字符串时对其进行转义 (ideone):您还可以考虑避免使用正则表达式,而只使用普通字符串方法 ( ideone):
The pipes in your regular expression are being interpreted as the alternation operator. Your regular expression will replace the following three strings:
You can solve your problem by using
Regexp.escape
to escape the string when you use it in a regular expression (ideone):You could also consider avoiding regular expressions and just using the ordinary string methods instead (ideone):
管道是正则表达式语法的一部分(它们的意思是“或”)。您需要使用反斜杠对它们进行转义,以便将它们算作要匹配的实际字符。
Pipes are part of regexp syntax (they mean "or"). You need to escape them with a backslash in order to have them count as actual characters to be matched.