RegExp 的 exec() 函数和 String 的 match() 函数有什么区别? [英] What is the difference between RegExp’s exec() function and String’s match() function?
本文介绍了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屋!
查看全文