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

问题描述:

我想从notes删除从example_header开始的一切。我试图做的:为什么在Ruby中不使用“gsub”删除管道?

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 
    || 

为什么||不会被删除?

正则表达式中的管道被解释为alternation operator。正则表达式将取代以下三个字符串:

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

当你在一个正则表达式(ideone)使用它您可以通过使用Regexp.escape逃避串解决您的问题:

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

你可以还考虑避免使用正则表达式,而只是使用普通字符串方法(ideone):

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

谢谢!你能不能建议一种无正则表达式的方法? – 2012-01-29 22:05:23

+1

@Progrog:这不起作用,因为Misha想要删除标题*以及其后的所有内容*。 – 2012-01-29 22:15:21

管道是regexp语法的一部分(它们表示“或”)。您需要使用反斜杠将它们转义,以便让它们作为实际字符进行匹配。