9

我在java脚本中有以下代码

    var regexp = /\$[A-Z]+[0-9]+/g;
    for (var i = 0; i < 6; i++) {
        if (regexp.test("$A1")) {
            console.log("Matched");
        }
        else {
            console.log("Unmatched");
        }
    }

请在您的浏览器控制台上运行它。它将打印替代MatchedUnmatched。谁能说出它的原因。

4

4 回答 4

4

调用test字符串后,lastIndex指针将在匹配后设置。

Before:
$A1
^

After:
$A1
   ^

当它到达结尾时,指针将被重置到字符串的开头。

你可以试试'$A1$A1',结果是

Matched
Matched
Unmatched
...

此行为在 15.10.6.2, ECMAScript Language Spec中定义。

步骤 11. 如果 global 为真,a。lastIndex使用参数“ ”、e 和 true调用 R 的 [[Put]] 内部方法。

于 2013-01-31T03:58:35.057 回答
1

我已将您的代码缩小为一个简单的示例:

var re = /a/g, // global expression to test for the occurrence of 'a'
s = 'aa';     // a string with multiple 'a'

> re.test(s)
  true
> re.lastIndex
  1
> re.test(s)
  true
> re.lastIndex
  2
> re.test(s)
  false
> re.lastIndex
  0

这只发生在全局正则表达式中!

来自MDN 文档.test()

exec(或与其结合)一样,test在同一个全局正则表达式实例上多次调用将超过前一个匹配项。

于 2013-01-31T04:46:24.363 回答
0

这是因为您使用全局标志g,每次调用.test时,.lastIndex正则表达式对象的属性都会更新。

如果您不使用该g标志,那么您可能会看到不同的结果。

于 2013-01-31T04:03:23.930 回答
0

第一行中的“g”不正确,您不是在此处执行替换,而是匹配,删除它,您将获得预期的行为。

var 正则表达式 = /\$[AZ]+[0-9]+/g; 应该是: var regexp = /\$[AZ]+[0-9]+/

于 2013-01-31T04:04:33.163 回答