2010-11-11 45 views

回答

0

沒有沒有一個隱含的^。但是,開始處的空字符串與正則表達式/[0-9]*/匹配,因此返回""

,可以查看的匹配處理(不/g標誌)是這樣的:

for (cursor in [0, 1, .. string.length-1]) 
    if (the regex matches string.substr(cursor) with an implicit '^') 
    return the match; 
return null; 
"0 Y" -> find longest match for [0-9]* from the current cursor index (beginning) 
     -> found "0" with * = {1} 
     -> succeed, return. 

"Y 0" -> find longest match for [0-9]* from the current cursor index (beginning) 
     -> found "" with * = {0} 
     -> succeed, return. 

因此應該避免空字符串匹配正則表達式。如果您需要確保數字匹配,請使用+

"0 Y".match(/\d+/) 
4

不,它沒有隱含的^

*表示匹配零個或多個字符,因爲在字符串的開頭有零位,它匹配並返回一個空字符串。

+0

那麼,爲什麼它不爲「0 Y」的開頭匹配「空字符串」,而是繼續進行,直到它找到0? – AndreKR 2010-11-11 18:02:05

+0

因爲它從第一個位置開始就很貪婪,並且儘可能匹配它。 – rampion 2010-11-11 18:03:15

+0

@AndreKR - 空字符串在'0'之後,它首先匹配它,再次嘗試'「0 Y」.match(/ [0-9] */g)'看到這個。 – 2010-11-11 18:03:40

2

我想你以後就是:

"0 Y".match(/[0-9]/) // returns "0" 

"Y 0".match(/[0-9]/) // returns "0" 

您當前*版本匹配0 以上號......所以一個空字符串匹配。試試這個作爲一個例子,以獲得更清晰的視野:

"Y 0".match(/[0-9]*/g) // matches: "", "0", ""