为什么Regex Javascript // g标志影响状态? [英] Why is Regex Javascript //g flag affecting state?

查看:90
本文介绍了为什么Regex Javascript // g标志影响状态?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有另一个问题,虽然有人回答我不明白为什么正则表达式会受到影响它的方式

I had another question and although it was answered i dont understand WHY the regex is affected the way it is

来自 w3schools 它说


g:执行全局匹配(找到所有匹配而不是在第一次匹配后停止)

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

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

Ok sure. I understand. Thats why i get an array in this code

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

输出:

ain,AIN,ain,ain 

正则表达式类似, / g 它将替换多个实例。

Regex is similar, with /g it will replace more than one instance.

然而在比赛中

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

结果是真假。

现在为什么$%^&它做到了吗?两个测试中的字符串完全相同!在过去,我认为全球意味着它将搜索新行(这是我想在此测试中做的)。我引用的第一件事就是g是一场全球比赛。

Now why the $%^& does it do that? The string in both test are exactly the same! In the past i thought global meant it will search across newlines (which is what i wanted to do in this test). The very first thing i quoted was about g being a global match.

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

Nothing makes any reference about it affecting the NEXT CALL! without /g the code will work correctly (also i dont need to go across newlines). WHY is it affecting the next test? gumbo answer makes mention it affects the lastIndex across calls and what the %^&* i had no idea there is shared state as the other two functions made no use of it while i used the g flag. I only wanted a true and false but if anything shouldnt match return an int containing the amount of matches it found globally? (ie 1 in "hi" but 2 in the string "hihi").

为什么在执行regex.test时,heg是否会影响我的下一个调用?!另外,如果可以的话,提供当我真正想要'功能'

Why the heck is g affecting my next call when doing regex.test?! Also if you can, provide when i'd actually want that 'feature'

推荐答案

当你在正则表达式中使用全局标志时,lastIndex属性已更新。 lastIndex属性是开始下一场比赛的索引。

When you use the global flag in the regex, the lastIndex property is updated. The lastIndex property is the index at which to start the next match.

https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/RegExp

你可以在再次呼叫之前重置最后一个索引。见

You can reset the last index before calling again. See

为什么在Javascript中使用全局标志的RegExp会给出错误的结果?

这篇关于为什么Regex Javascript // g标志影响状态?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆