在线观看不卡亚洲电影_亚洲妓女99综合网_91青青青亚洲娱乐在线观看_日韩无码高清综合久久

鍍金池/ 問(wèn)答/Java  HTML/ 為什么這條正則全局匹配是錯(cuò)的?

為什么這條正則全局匹配是錯(cuò)的?

為什么這條正則全局匹配是錯(cuò)的?
原碼如下:

var str='13662890478';
        var reg=/^1[3|5|8]\d{9}/g;
        var result=reg.exec(str);
        if(reg.test(str)){
            console.log('對(duì)')
            console.log(result[0])
        }else{
            console.log('錯(cuò)')
            console.log(result[0])
        }

圖片描述

回答
編輯回答
單眼皮

文檔 官方文檔有講

2017年9月26日 23:14
編輯回答
吢涼

/^1[3|5|8]\d{9}$/; // 修正一下你的正則, 這樣會(huì)可靠點(diǎn) 如果只是為了驗(yàn)證手機(jī)號(hào)格式

帶g 的如果用了 exec 一個(gè)字符串做匹配,會(huì)有緩存問(wèn)題,按你想要的效果,你可以在 reg.test(str) 之前 把 reg.lastIndex = 0; 這個(gè)用上

2017年10月29日 09:05
編輯回答
九年囚

js 正則匹配在全局匹配模式下可以對(duì)指定要查找的字符串執(zhí)行多次匹配。每次匹配使用當(dāng)前正則對(duì)象的lastIndex屬性的值作為在目標(biāo)字符串中開(kāi)始查找的起始位置。lastIndex的初始值為0,找到匹配的項(xiàng)后lastIndex的值被重置為匹配內(nèi)容的下一個(gè)字符在字符串中的位置索引,如果找不到匹配的項(xiàng)lastIndex的值會(huì)被設(shè)置為0。你說(shuō)的情況是正好在lastIndex為11的值,你可以這樣測(cè)試下:

var str='13662890478';
var reg=/^1[3|5|8]\d{9}/g
console.log(reg.lastIndex)
console.log(reg.test(str))
console.log(reg.lastIndex)      
console.log(reg.test(str))
console.log(reg.lastIndex)
console.log(reg.test(str))
console.log(reg.lastIndex)      
console.log(reg.test(str))
2017年10月21日 09:22
編輯回答
卟乖

應(yīng)該是lastIndex的問(wèn)題,因?yàn)槟阋呀?jīng)使用exec調(diào)用過(guò)一次,正則的lastIndex變了,再次調(diào)用test就會(huì)出現(xiàn)這種情況。

var str='13662890478';
var reg=/^1[3|5|8]\d{9}/g;
reg.test(str) // true
reg.test(str) // false

你會(huì)發(fā)現(xiàn)多次調(diào)用會(huì)false和true循環(huán)變化。

2017年10月23日 07:16