2015-01-21 16 views
0

我有兩個正則表達式,一個是^0|[1-9][0-9]*$,另一個是^(0|[1-9][0-9]*),第一個表達式與字符串"01"匹配,而後者不能。這兩個表達式有什麼區別?在我看來,後者只捕獲匹配的字符串。我想知道爲什麼後面的不能匹配"01"字符串。OR運算符在正則表達式中捕獲與否的不同行爲

+2

在第二個正則表達式中不應該有'$'? – 2015-01-21 12:21:52

回答

6

見圖表解釋

^0|[1-9][0-9]*$ 

Regular expression visualization

Debuggex Demo

對戰

^(0|[1-9][0-9]*)$ 

Regular expression visualization

Debuggex Demo

所以第二正則表達式需要字符串爲「0」或1-9字符開始。

1

看它們是這樣的:

^0   # Match a 0 at the start of the string 
|    # or 
[1-9][0-9]*$ # match a number > 1 at the end of the string. 

^    # Match the start of the string. 
(   # Start of group 1: 
0   # Match a zero 
|    # or 
[1-9][0-9]* # a number > 1. 
)    # End of group 1. 
$    # Match the end of the string. 

而它包含在第二示例中的組內的交替延伸到在第一實施例的錨定件。