2015-11-09 78 views
0

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

顺便说一句,请建议更精美的方式来捕捉这样的字符串。 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| 

我曾尝试使用这种正则表达式,用于捕获第一和secodn类型串的任何正数(不相同)

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

零应作为独立炭进行处理, 我需要捕捉每个号码或零

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

但没有捕获其他数字

请这个正则表达式的帮助,如果有人提供了更多的elagant方式,将是巨大的(在最后,我必须写4个ORS语句来捕捉我的字符串类型)

感谢

回答

1

我不知道wheter就足够了,你还是不:

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

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

现在你必须将你的匹配分成x个元素组,其中x是柱子的数量。我想这应该会很好。

0

如何:

^(?:\|[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 

这将匹配你给了所有的例子,即。一些正数,后面跟零。

0

你可以先验证该行,那么就用\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