2010-09-02 43 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