RegExp的exec()函数和String的match()函数有什么区别? [英] What is the difference between RegExp’s exec() function and String’s match() function?

查看:146
本文介绍了RegExp的exec()函数和String的match()函数有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我运行:

/([^\/]+)+/g.exec('/a/b/c/d');

我明白了:

["a", "a"]

但是如果我运行这个:

'/a/b/c/d'.match(/([^\/]+)+/g);

然后我得到了预期的结果:

Then I get the expected result of this:

["a", "b", "c", "d"]

有什么区别?

推荐答案

exec 使用全局正则表达式意味着在循环中使用,因为它仍将检索所有匹配的子表达式。所以:

exec with a global regular expression is meant to be used in a loop, as it will still retrieve all matched subexpressions. So:

var re = /[^\/]+/g;
var match;

while (match = re.exec('/a/b/c/d')) {
    // match is now the next match, in array form.
}

// No more matches.

String.match 为您和丢弃捕获的组。

String.match does this for you and discards the captured groups.

这篇关于RegExp的exec()函数和String的match()函数有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆