我有以下代码:
var str = "4 shnitzel,5 ducks";
var rgx = new RegExp("[0-9]+","g");
console.log( rgx.exec(str) );
Run Code Online (Sandbox Code Playgroud)
chrome和firefox的输出是["4"].
为什么我没有得到结果["4","5"]?
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]);
}
Run Code Online (Sandbox Code Playgroud)
或者你只是在字符串`str上使用match方法:
var str = "4 shnitzel,5 ducks",
re = new RegExp("[0-9]+","g"),
matches = str.match(re);
Run Code Online (Sandbox Code Playgroud)
顺便说一句:使用RegExp文字语法/…/可能更方便:/[0-9]+/g.
| 归档时间: |
|
| 查看次数: |
1489 次 |
| 最近记录: |