2010-09-02 17 views

回答

6

exec不會只搜索下一個比賽。您需要多次調用以獲取所有匹配項:

如果您的正則表達式使用「g」標誌,則可以多次使用exec方法在同一個字符串中查找連續匹配。

可以做到這一點找到所有比賽用exec

var str = "4 shnitzel,5 ducks", 
    re = new RegExp("[0-9]+","g"), 
    match, matches = []; 
while ((match = re.exec(str)) !== null) { 
    matches.push(match[0]); 
} 

,或者你只是使用弦上match method`STR:

var str = "4 shnitzel,5 ducks", 
    re = new RegExp("[0-9]+","g"), 
    matches = str.match(re); 

順便說一句:使用RegExp literal syntax /…/可能更方便:/[0-9]+/g

2

exec()總是隻返回一個匹配。你需要進一步匹配你需要反覆調用exec。

https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/RegExp/exec

+0

如果您的正則表達式使用「g」標誌,則可以多次使用exec方法在同一個字符串中查找連續的匹配項。當您這樣做時,搜索將從正則表達式的lastIndex屬性指定的str的子字符串開始(test還會提前執行lastIndex屬性)。 – 2013-08-06 07:35:42