为什么Javascript的regex.exec()并不总是返回相同的值? [英] Why does Javascript's regex.exec() not always return the same value?
问题描述
在Chrome或Firebug控制台中:
In the Chrome or Firebug console:
reg = /ab/g
str = "abc"
reg.exec(str)
==> ["ab"]
reg.exec(str)
==> null
reg.exec(str)
==> ["ab"]
reg.exec(str)
==> null
exec在某种程度上是有状态的,取决于它上一次返回的内容吗?或者这只是一个错误?我无法让它一直发生。例如,如果上面的'str'是abc abc则不会发生。
Is exec somehow stateful and depends on what it returned the previous time? Or is this just a bug? I can't get it to happen all the time. For example, if 'str' above were "abc abc" it doesn't happen.
推荐答案
一个JavaScript RegExp
对象是有状态的。
A JavaScript RegExp
object is stateful.
当正则表达式是全局的时,如果你调用一个方法相同的正则表达式对象,它将从索引超过最后一场比赛结束。
When the regex is global, if you call a method the same regex object, it will start from the index past the end of the last match.
当找不到更多匹配项时,索引将重置为 0
自动。
When no more matches are found, the index is reset to 0
automatically.
要手动重置,请设置 lastIndex
属性。
To reset it manually, set the lastIndex
property.
reg.lastIndex = 0;
这可能是一个非常有用的功能。如果需要,您可以在字符串中的任何位置开始评估,或者如果在循环中,您可以在所需数量的匹配后停止评估。
This can be a very useful feature. You can start the evaluation at any point in the string if desired, or if in a loop, you can stop it after a desired number of matches.
这是一个在循环中使用正则表达式的典型方法的演示。它通过执行赋值作为循环条件,当没有更多匹配时, exec
返回 null
这一事实。
Here's a demonstration of a typical approach to using the regex in a loop. It takes advantage of the fact that exec
returns null
when there are no more matches by performing the assignment as the loop condition.
var re = /foo_(\d+)/g,
str = "text foo_123 more text foo_456 foo_789 end text",
match,
results = [];
while (match = re.exec(str))
results.push(+match[1]);
DEMO: http://jsfiddle.net/pPW8Y/
如果您不喜欢分配的位置,可以重新设置循环,例如......
If you don't like the placement of the assignment, the loop can be reworked, like this for example...
var re = /foo_(\d+)/g,
str = "text foo_123 more text foo_456 foo_789 end text",
match,
results = [];
do {
match = re.exec(str);
if (match)
results.push(+match[1]);
} while (match);
DEMO: http://jsfiddle.net/pPW8Y/1/
这篇关于为什么Javascript的regex.exec()并不总是返回相同的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!