gpt4 book ai didi

javascript - 带有全局标志的 JavaScript 中的正则表达式

转载 作者:行者123 更新时间:2023-11-29 19:03:58 27 4
gpt4 key购买 nike

RegExp 内在函数似乎是有状态的。

因此,当提供全局标志 g 时,在同一个字符串上调用它两次将产生不同的结果,因为它会沿着字符串进行搜索。

所以:

var r = /(\d{3})/g;

console.log(r.test('123')); // true
console.log(r.test('123')); // false - because the search has moved past the first match

但是如果我添加一个中间测试,我会得到以下结果:

var r = /(\d{3})/g;

console.log(r.test('123')); // true
console.log(r.test('456')); // true
console.log(r.test('123')); // true!

那么说 RegExp 实例根据只考虑最后计算的字符串的原则运行是正确的吗?如果字符串与上一个不同,它是否有效重置?

最佳答案

So is it correct to say that RegExp instances operate on the principle of considering only the last string evaluated?

是的

If the string differs from the last, it is effectively reset?

正确

If the global flag is omitted, is the regular expression reset in between tests?

查看 RegExp#lastIndex

关于javascript - 带有全局标志的 JavaScript 中的正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44431188/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com