When calling String.replace with a replacement function we're able to retrieve offsets of the matched substrings.
当调用字符串。替换为替换函数,我们可以检索匹配的子字符串的偏移量。
var a = [];
"hello world".replace(/l/g, function (m, i) { a.push(i); });
// a = [2, 3, 9]
In the example above, we're getting a list of offsets for the matching l
characters.
在上面的示例中,我们得到了匹配的l字符的偏移量列表。
Can I count on implementations to always invoke the match function in ascending order of occurrence? That is: Can I be sure that the result above will always be [2,3,9]
and not [3,9,2]
or any other permutation of those offsets?
我能指望实现总是按事件的升序调用match函数吗?也就是说:我能确定上面的结果将永远是[2,3,9]而不是[3,9,2]或这些偏移的任何其他排列吗?
I've looked at the specification and I cannot find anything that specifies the order of invocation, but perhaps this is implied by how the regular expression engine is supposed to be implemented?
我已经查看了规范,我找不到任何指定调用顺序的东西,但是可能这是通过正则表达式引擎应该实现的方式来暗示的。
2 个解决方案
#1
3
Can I count on implementations to always invoke the match function in ascending order of occurrence?
我能指望实现总是按事件的升序调用match函数吗?
Absolutely, yes. Matches are handled from left to right in the source string because left-to-right is how regular expression engines work their way to a string.
绝对是的。在源字符串中,从左到右处理匹配,因为从左到右是正则表达式引擎的工作方式。
#2
0
I think you shouldn't worry about it. Also you can use the Fookahead
pattern, which going from the start of the string:
我认为你不应该为此担心。你也可以使用Fookahead模式,它从字符串的开头开始:
"hello world".replace(/(?=l)/g, function (m, i) { a.push(i); });
#1
3
Can I count on implementations to always invoke the match function in ascending order of occurrence?
我能指望实现总是按事件的升序调用match函数吗?
Absolutely, yes. Matches are handled from left to right in the source string because left-to-right is how regular expression engines work their way to a string.
绝对是的。在源字符串中,从左到右处理匹配,因为从左到右是正则表达式引擎的工作方式。
#2
0
I think you shouldn't worry about it. Also you can use the Fookahead
pattern, which going from the start of the string:
我认为你不应该为此担心。你也可以使用Fookahead模式,它从字符串的开头开始:
"hello world".replace(/(?=l)/g, function (m, i) { a.push(i); });