为什么“pattern.test(name)”连续调用的结果是相反的?

Why `pattern.test(name)` opposite results on consecutive calls

本文关键字:调用 结果是 连续 pattern test name 为什么      更新时间:2023-09-26

为什么这段代码先返回真,然后返回假

var pattern = new RegExp("mstea", 'gi'), name = "Amanda Olmstead";
console.log('1', pattern.test(name));
console.log('1', pattern.test(name));

演示:小提琴

g用于重复搜索。它将正则表达式对象更改为迭代器。如果您想使用test函数根据模式检查字符串是否有效,请删除此修饰符:

var pattern = new RegExp("mstea", 'i'), name = "Amanda Olmstead";

replacematch相反,test函数不消耗整个迭代,这使其处于"坏"状态。在使用test函数时,可能永远不应该使用这个修饰符。

不要将gi与pattern.test结合使用。g标志意味着它跟踪您正在运行的位置,以便可以重用它。因此,您应该使用:

var pattern = new RegExp("mstea", 'i'), name = "Amanda Olmstead";
console.log('1', pattern.test(name));
console.log('1', pattern.test(name));

也可以用/…/[flags] regex的语法,像这样:

var pattern = /mstea/i;

因为你设置了g修饰符

为您的案例删除它。

var pattern = new RegExp("mstea", 'i'), name = "Amanda Olmstead";

它不是一个错误。

g使它在第一次匹配之后对子字符串执行下一次尝试匹配。这就是为什么它在每一次偶数尝试中返回false。

First attempt: 
It is testing "Amanda Olmstead"
Second attempt:
It is testing "d" //match found in previous attempt (performs substring there)
Third attempt:
It is testing "Amanda Olmstead" again //no match found in previous attempt
... so on

Regexp.exec状态的MDN页面:

如果你的正则表达式使用"g"标志,你可以使用exec方法多次查找同一字符串中的连续匹配项。指定str的子字符串开始搜索正则表达式的lastIndex属性

test状态的MDN页面:

与exec(或与其组合)一样,多次调用test对于相同的全局正则表达式实例,将向前推进到之前的比赛。