gpt4 book ai didi

javascript - 为什么 Regex Javascript//g 标志会影响状态?

转载 作者:搜寻专家 更新时间:2023-11-01 05:06:49 25 4
gpt4 key购买 nike

<分区>

我有 another question虽然它得到了回答,但我不明白为什么正则表达式会受到影响

来自 w3schools它说

g: Perform a global match (find all matches rather than stopping after the first match)

好的,当然。我明白。这就是为什么我在这段代码中得到一个数组

var str="The rain in SPAIN stays mainly in the plain";
var patt1=/ain/gi;
document.write(str.match(patt1));

输出:

ain,AIN,ain,ain 

Regex 类似,用/g 会替换多个实例。

然而在比赛中

var re=/hi/gi;
alert(re.test("hi") + " " + re.test("hi"));

结果是“真假”。

那么为什么 $%^& 这样做呢?两个测试中的字符串完全相同!过去我认为全局意味着它将搜索换行符(这是我想在这个测试中做的)。我引用的第一件事是关于 g 是全局匹配。

没有任何关于它影响 NEXT CALL 的引用!没有/g 代码将正常工作(我也不需要跨行)。为什么它会影响下一次测试? gumbo 回答提到它会影响跨调用的 lastIndex 以及 %^&* 我不知道有共享状态的内容,因为在我使用 g 标志时其他两个函数没有使用它。我只想要一个 true 和 false,但如果有任何不匹配的东西返回一个包含它在全局范围内找到的匹配数量的 int? (即“hi”中有 1 个,但字符串“hihi”中有 2 个)。

为什么在进行 regex.test 时 g 会影响我的下一次调用?!另外,如果可以的话,请提供我真正需要该“功能”的时间

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