我想从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
||
为什么不删除||
?
答案 0 :(得分:7)
正则表达式中的管道被解释为alternation operator。您的正则表达式将替换以下三个字符串:
"-----------------\n---"
" Example "
"---\n-----------------"
在正则表达式(Regexp.escape
)中使用字符串时,可以使用ideone来转义字符串来解决问题:
puts notes.gsub(Regexp.new(Regexp.escape(example_header) + ".*",
Regexp::MULTILINE),
"")
您还可以考虑避免使用正则表达式,而只使用普通的字符串方法(ideone):
puts notes[0, notes.index(example_header)]
答案 1 :(得分:3)
管道是regexp语法的一部分(它们的意思是“或”)。您需要使用反斜杠来转义它们,以便将它们计为要匹配的实际字符。