2015-11-09 139 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