【问题标题】:Capture groups match with quantifier Regexp捕获组与量词 Regexp 匹配
【发布时间】:2015-11-09 09:41:51
【问题描述】:

我是正则表达式世界的新手,我需要捕获一些不同类型的字符串。

顺便请建议更优雅的方式来捕获这些字符串。 n = 任意正数(不相同)

|n||0||0||0||0|
|n||n||0||0||0|
|n||n||n||0||0|
|n||n||n||n||0|
|n||n||n||n||n|

我已经尝试使用这样的正则表达式来捕获第一个和第二个类型的字符串

^\|([1-9]+)\|(?:([1-9]+)\|){4}|(?:(0)\|){4}$

零应该被视为单独的字符, 我需要捕获每个数字或零

现在的问题是它只捕获第一个匹配的字符和最后一个

但不捕获其他数字

请帮助这个正则表达式,如果有人提供更优雅的方式会很棒(最后,我必须编写 4 个 ors 语句来捕获我的字符串类型)

谢谢

【问题讨论】:

    标签: php regex preg-match regex-lookarounds


    【解决方案1】:

    我不确定这对你是否足够:

    \|(?:(0)|([0-9]+))\|
    

    https://regex101.com/r/fX5xI4/2

    现在您必须将匹配项分成 x 个元素组,其中 x 是列数。我想应该没问题。

    【讨论】:

      【解决方案2】:

      怎么样:

      ^(?:\|[1-9][0-9]*\|){1,5}(?:\|0\|){0,4}$
      

      说明:

      ^               : start of line
        (?:           : non capture group
         \|           : a pipe character
         [1-9][0-9]*  : a positive number of any length
         \|           : a pipe character
        ){1,5}        : the group is repeated 1 to 5 times
        (?:           : non capture group
          \|0\|       : a zero with pipe arround it
        ){0,4}        : group is repeated 0 to 4 times.
      $               : end of line
      

      这将匹配您给出的所有示例,即。一些正数后跟零。

      【讨论】:

        【解决方案3】:

        您可以先验证该行,然后使用\d+ findall

        验证:'~^\|[1-9]\d*\|(?:\|(?:[1-9]\d*|0+(?!\|\|[1-9]))\|){4}$~'

         ^                             # BOS
         \|
         [1-9] \d*                     # Any numbers that start with non-zero
         \|
        
         (?:
              \|
              (?:
                   [1-9] \d*                     # Any numbers that start with non-zero
                |                              # or,
                   0+                            # Any numbers with all zeros
                   (?! \|\| [1-9] )              # Not followed by a non-zero
              )
              \|
         ){4}
         $                             # EOS
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2019-07-25
          • 1970-01-01
          • 2011-12-21
          • 2012-06-22
          • 2012-06-07
          • 2012-03-07
          • 2016-12-17
          相关资源
          最近更新 更多