简体   繁体   English

捕获组与量词Regexp匹配

[英]Capture groups match with quantifier Regexp

I am newbie in regex world, I need to capture some different types of strings. 我是regex世界的新手,我需要捕获一些不同类型的字符串。

By the way please suggest more elagant way to capture such strings. 顺便说一句,请提出更愚蠢的方式来捕获这样的字符串。 n = any positive number(not the same) 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|

I have tried to use such regular expression for capturing first and secodn types of strings 我试图使用这样的正则表达式来捕获字符串的第一和第二类型

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

Zero should be treated as separate char, I need to capture each number or zero 零应视为单独的字符,我需要捕获每个数字或零

The problem now that it only captures first matched character and last one 现在的问题是,它仅捕获第一个匹配的字符和最后一个匹配的字符

But doesn't capture other digits 但不捕获其他数字

Please help with this regular expression and it would be great if someone provides more elagant way ( at the end, I have to write 4 ors statements to capture my string types) 请提供此正则表达式帮助,如果有人提供更多无关紧要的方法,那将非常有用(最后,我必须编写4个ors语句来捕获我的字符串类型)

Thanks 谢谢

I'm not sure wheter it is sufficient for you or not: 我不确定这是否足以满足您的需求:

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

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

Now u have to split your matches into groups of x elements where x is number of colums. 现在,您必须将匹配项分成x个元素组,其中x是列数。 I suppose that should be just fine. 我想那应该没问题。

How about: 怎么样:

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

Explanation: 说明:

^               : 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

This will match all examples you've given, ie. 这将匹配您提供的所有示例。 some positive numbers followed by zeros. 一些正数后跟零。

You could validate the line first, then just findall with \\d+ 您可以先验证行,然后使用\\d+查找全部

Validate: '~^\\|[1-9]\\d*\\|(?:\\|(?:[1-9]\\d*|0+(?!\\|\\|[1-9]))\\|){4}$~' 验证: '~^\\|[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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM