javascript中的正则表达式每次都以相同的输入失败 [英] Regex in javascript fails every other time with identical input

查看:75
本文介绍了javascript中的正则表达式每次都以相同的输入失败的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

一个简单的测试脚本:

<script type="text/javascript">
    var reg = new RegExp('#([a-f0-9]{3})$', 'gi');
    for (var i = 0; i < 10; i++) {
        console.log(reg.exec('#fff'));
    }
</script>

控制台输出:

["#fff", "fff"]
null
["#fff", "fff"]
null
["#fff", "fff"]
null
["#fff", "fff"]
null
["#fff", "fff"]
null

当输入保持不变时,为什么其他每个结果都为空?

推荐答案

使用全局标志时,正则表达式变为粘滞。也就是说,它使用计数器变量来跟踪找到最后一个匹配项的 。而不是每次从头开始匹配,粘性正则表达式实际上将在最后一个匹配结束的地方拾取。如果整个匹配失败,这个计数器只会重置为0(开头)(这就是为什么它每隔一次都有效)

When you use the global flag, the regex becomes "sticky." That is to say, it uses a counter variable to track where the last match was found. Rather than matching from the beginning each time, a sticky regex will actually pick up where the last match ended. This counter will only reset back to 0 (the beginning) if the entire match fails (which is why it works every-other-time)

在你的情况下,我的建议将删除 g 标志。

In your case, my suggestion would be to drop the g flag.

有关详细信息: RegExp @ MDC

这篇关于javascript中的正则表达式每次都以相同的输入失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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