正则捕获以及懒惰性解决方法

let str = 'hjfhdsjfs2020@@@2019jfjdhfjsd2018';
// let reg =/^d+/;
// //=>实现正则捕获的前提是:当前正则要和字符串匹配,如果不匹配捕获的结果是null
// console.log(reg.test(str)); //false
// console.log(reg.exec(str)); //null


/*基于exec实现正则的捕获
1.捕获到的结果是null或者一个数组
数组第一项:本次捕获到的内容
其余项:对应小分组本次单独捕获的内容
index:当前捕获内容在字符串中的起始索引
input:原始字符串
2.每执行一次exec,只能捕获到一个符合正则规则的,但是默认情况下,我们执行一百遍,获取的结果永远都是第一个匹配到的,其余的捕获不到
=>正则规则的懒惰性:默认只捕获第一个
*/
/*lastIndex:当前正则下一次匹配的起始索引位置
懒惰性捕获的原因;默认情况下lastIndex的值不会被修改,每一次都是从字符串开始位置查找,所以找到的永远只是第一个
解决的办法:全局是从字符串最开始找,找到的永远是第一个匹配到的
*/
// let reg = /d+/;
// console.log(reg.exec(str)); // =>['2020',index:9,input:'hjfhdsjfs2020@@@2019jfjdhfjsd2018',groups:undefined]
// console.log(reg.lastIndex); // 0 下面匹配捕获是从str索引0的位置开始找
// console.log(reg.exec(str)); // =>['2020',index:9,input:'hjfhdsjfs2020@@@2019jfjdhfjsd2018',groups:undefined]
// console.log(reg.lastIndex);// 0 第一次匹配捕获完成,lastIndex没有完成改变,所以下一次exec依然是从字符串最开始找,找到的永远是第一个匹配到的
 
 
// let reg = /d+/g;
// console.log(reg.exec(str)); //["2020", index: 9, input: "hjfhdsjfs2020@@@2019jfjdhfjsd2018", groups: undefined]
// console.log(reg.lastIndex); //13 设置全局匹配修饰符g后,第一次匹配完
// console.log(reg.exec(str)); //["2019", index: 16, input: "hjfhdsjfs2020@@@2019jfjdhfjsd2018", groups: undefined]
// console.log(reg.lastIndex); //20
// console.log(reg.exec(str)); //["2018", index: 29, input: "hjfhdsjfs2020@@@2019jfjdhfjsd2018", groups: undefined]
// console.log(reg.lastIndex); //33
// console.log(reg.exec(str)); //null 当全部捕获后,再次捕获的结果是null,但是lastIndex又回了初始值0,再次捕获又重新开始了
// console.log(reg.lastIndex); //0
// console.log(reg.exec(str)); //["2020", index: 9, input: "hjfhdsjfs2020@@@2019jfjdhfjsd2018", groups: undefined]
 

/*
不能这么判断,因为懒惰性和lastIndex值
*/
// let reg = /d+/g;
// if(reg.test(str)){
// //验证一下,只有验证和字符串匹配我们在捕获
// console.log(reg.lastIndex); // 13 基于test匹配验证后,lastIndex已经被修改为第一次匹配后的结果,所以下一次捕获不再从头开始了
// console.log(reg.exec(str)); //["2019", index: 16, input: "hjfhdsjfs2020@@@2019jfjdhfjsd2018", groups: undefined]
// }


 
//懒惰性的解决方法
//需求:编写一个方法execAll,执行一次可以把所有匹配的结果捕获到(前提正则一定要设置全局修饰符g)
~function(){
function execAll(str = ''){
//str:要匹配的字符串
//this:RegExp的实例(当前操作的正则)
//进来后的第一件事,是验证当前正则是否设置了g,不设置则不能在进行循环捕获了,否则会导致死循环
//ary:存储最后所有捕获的信息,res存储每一次捕获的内容
if(!this.global) return this.exec(str)
let ary = [],
res = this.exec(str)
while(res){
//把每一次捕获的内容res[0]存放到数组中
ary.push(res[0]);
//只要捕获的内容不为null,则继续捕获下去
res = this.exec(str);
}
return ary.length === 0 ? null : ary
}
RegExp.prototype.execAll = execAll;
}()
let reg = /d+/g;
console.log(reg.execAll('hhhh2sh22')); //["2", "22"]
//字符串中match方法,可以执行一次的情况下,捕获到所有匹配的数据(前提:正则也得设置g才可以)
console.log('hhhh2sh22'.match(reg)); //["2", "22"]
原文地址:https://www.cnblogs.com/itsmart/p/12679089.html