简体   繁体   English

为什么在Ruby中不使用“gsub”删除管道?

[英]Why pipes are not deleted using “gsub” in Ruby?

I would like to delete from notes everything starting from the example_header . 我想从删除notes一切从开始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? 是不是已删除?

The pipes in your regular expression are being interpreted as the alternation operator . 正则表达式中的管道被解释为交替运算符 Your regular expression will replace the following three strings: 您的正则表达式将替换以下三个字符串:

"-----------------\n---"
" Example "
"---\n-----------------"

You can solve your problem by using Regexp.escape to escape the string when you use it in a regular expression ( ideone ): 在正则表达式( ideone )中使用它时,可以使用Regexp.escape来转义字符串来解决问题:

puts notes.gsub(Regexp.new(Regexp.escape(example_header) + ".*",
                           Regexp::MULTILINE),
                "")

You could also consider avoiding regular expressions and just using the ordinary string methods instead ( ideone ): 您还可以考虑避免使用正则表达式,而只使用普通的字符串方法( ideone ):

puts notes[0, notes.index(example_header)]

Pipes are part of regexp syntax (they mean "or"). 管道是regexp语法的一部分(它们的意思是“或”)。 You need to escape them with a backslash in order to have them count as actual characters to be matched. 您需要使用反斜杠转义它们,以便将它们计为要匹配的实际字符。

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

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