【问题标题】:Regexp in ruby - can I use parenthesis without grouping?ruby 中的正则表达式 - 我可以使用括号而不分组吗?
【发布时间】:2011-08-24 22:50:39
【问题描述】:

我有一个形式的正则表达式:

/(something complex and boring)?(something complex and interesting)/

我对第二个括号的内容感兴趣;第一个只是为了确保正确匹配(因为无聊的部分可能存在也可能不存在,但如果存在,我会不小心将它与有趣部分的正则表达式匹配)。

所以我可以使用 $2 访问第二场比赛。但是,为了与我正在使用的其他正则表达式保持一致,我希望 $1 以某种方式包含第二个括号的内容。有可能吗?

【问题讨论】:

  • 感谢大家快速而有启发性的回答!

标签: ruby regex


【解决方案1】:

使用非捕获组:

r = /(?:ab)?(cd)/

【讨论】:

    【解决方案2】:

    这是一个非 ruby​​ 正则表达式功能。使用/(?:something complex and boring)?(something complex and interesting)/(注意?:)来实现这一点。

    顺便说一句,在 Ruby 1.9 中,您可以使用 /(something complex and boring)?(?<interesting>something complex and interesting)/ 并使用 $~[:interesting] 访问组;)

    【讨论】:

      【解决方案3】:

      是的,使用?: 语法:

      /(?:something complex and boring)?(something complex and interesting)/
      

      【讨论】:

        【解决方案4】:

        我不是 ruby​​ 开发人员,但我知道其他正则表达式风格。所以我打赌你可以使用非捕获组

        /(?:something complex and boring)?(something complex and interesting)/
        

        只有一个捕获组,因此 $1

        HTH

        【讨论】:

          【解决方案5】:

          不是真的,不。但是您可以使用命名组来保持一致性,如下所示:

          /(?<group1>something complex and boring)?(?<group2>something complex and interesting)/
          

          您可以更改名称(尖括号中的文本)以获得您想要实现的一致性。然后,您可以像这样访问组:

          string.match(/(?<group1>something complex and boring)?(?<group2>something complex and interesting)/) do |m|
              # Do something with the match, m['group'] can be used to access the group
          end
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2018-12-20
            • 1970-01-01
            • 1970-01-01
            • 2011-08-31
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多