代码之家  ›  专栏  ›  技术社区  ›  davidsmalley

Ruby中的动态正则表达式

  •  7
  • davidsmalley  · 技术社区  · 17 年前

    我试图找到一种方法,让我从一个字符串(取自数据库)动态创建一个regexp对象,然后用它过滤另一个字符串。本例是从git提交消息中提取数据,但理论上,任何有效的regexp都可以作为字符串存在于数据库中。

    发生了什么

    >> string = "[ALERT] Project: Revision ...123456 committed by Me <me@me.com>\n on 2009-   07-28 21:21:47\n\n    Fixed typo\n"
    >> r = Regexp.new("[A-Za-z]+: Revision ...[\w]+ committed by [A-Za-z\s]+")
    >> string[r]
    => nil
    

    >> string = "[ALERT] Project: Revision ...123456 committed by Me <me@me.com>\n on 2009-   07-28 21:21:47\n\n    Fixed typo\n"
    >> string[/[A-Za-z]+: Revision ...[\w]+ committed by [A-Za-z\s]+/]
    => "Project: Revision 123456 committed by Me"
    
    2 回复  |  直到 17 年前
        1
  •  11
  •   Gareth    17 年前

    >> Regexp.new "\w"
    => /w/
    >> Regexp.new "\\w"
    => /\w/
    

    反斜杠是字符串中的转义字符。如果你想要一个反斜杠,你必须加倍它。

    >> string = "[ALERT] Project: Revision ...123456 committed by Me <me@me.com>\n on 2009-   07-28 21:21:47\n\n    Fixed typo\n"
    => "[ALERT] Project: Revision ...123456 committed by Me <me@me.com>\n on 2009-   07-28 21:21:47\n\n    Fixed typo\n"
    >> r = Regexp.new("[A-Za-z]+: Revision ...[\\w]+ committed by [A-Za-z\\s]+")
    => /[A-Za-z]+: Revision ...[\w]+ committed by [A-Za-z\s]+/
    >> string[r]
    => "Project: Revision ...123456 committed by Me "
    

    通常,如果您粘贴了“断开”行的输出,而不仅仅是输入,您可能已经发现 w 和 s

        2
  •  0
  •   Swanand    17 年前

    备选案文1:

    # Escape the slashes:
    r = Regexp.new("[A-Za-z]+: Revision ...[\\w]+ committed by [A-Za-z\\s]+")
    

    缺点:手动转义所有已知转义字符

    备选案文2:

    # Use slashes in constructor
    r = Regexp.new(/[A-Za-z]+: Revision ...[\w]+ committed by [A-Za-z\s]+/)
    

    缺点:没有

    推荐文章