【问题标题】:Why pipes are not deleted using "gsub" in Ruby?为什么在 Ruby 中不使用“gsub”删除管道?
【发布时间】:2012-01-29 21:51:01
【问题描述】:

我想从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
    ||

为什么|| 没有被删除?

【问题讨论】:

    标签: ruby regex heredoc gsub


    【解决方案1】:

    正则表达式中的管道被解释为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)]
    

    【讨论】:

    • 谢谢!你能建议一种不用正则表达式来实现同样的方法吗?
    • @Phrogz:这行不通,因为 Misha 想删除标题 及其之后的所有内容
    【解决方案2】:

    管道是正则表达式语法的一部分(它们的意思是“或”)。您需要使用反斜杠对它们进行转义,以便将它们计为要匹配的实际字符。

    【讨论】:

      猜你喜欢
      • 2018-01-31
      • 2012-12-26
      • 1970-01-01
      • 2023-03-10
      • 1970-01-01
      • 1970-01-01
      • 2016-04-11
      • 2023-04-01
      • 2023-02-26
      相关资源
      最近更新 更多