gpt4 book ai didi

javascript - RegExp 不是确定性的吗?

转载 作者:行者123 更新时间:2023-12-01 00:50:45 25 4
gpt4 key购买 nike

我正在检查一个简单的正则表达式来检查一个单词是否有字母,因此我最终使用了类似的东西:

new RegExp(/[A-Z]/gi)

每次用户更改输入时都会执行/测试此正则表达式,假设输入速度非常快,所以我创建了这个小片段:

const hasLettersExpression = new RegExp(/[A-Z]/gi);
const hasLetters = str => hasLettersExpression.test(str);

for (let i = 0; i < 10; i++) {
// we always test against the same string.
console.log(i, '--->', hasLetters('12ab'))
}

从我的 Angular 来看,它给出了以下结果:

0 ---> true
1 ---> true
2 ---> false
3 ---> true
4 ---> true
5 ---> false
6 ---> true
7 ---> true
8 ---> false
9 ---> true

这是不正确的,因为它应该始终返回 true .

有谁知道为什么会这样吗?有一个true, true, false的模式...这有关系吗?

最佳答案

使用全局 'g' 标志创建的正则表达式将在调用 test 时记住最后的匹配索引。

If the regex has the global flag set, test() will advance the lastIndex of the regex. A subsequent use of test() will start the search at the substring of str specified by lastIndex (exec() will also advance the lastIndex property). It is worth noting that the lastIndex will not reset when testing a different string. (mdn)

const regex = new RegExp(/[A-Z]/gi);
const str = '12ab';

for (let i = 0; i < 10; i++)
console.log(i, '--->', regex.test(str), regex.lastIndex);

关于javascript - RegExp 不是确定性的吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56993383/

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