正则表达式的exec方法与字符串的match方法比较

本文探讨了正则表达式在全局属性下与非全局属性下的行为差异,通过实例展示了如何使用`exec`和`match`方法进行多次匹配,以及它们在不同属性设置下的表现。全局属性使得正则表达式能够遍历整个字符串,捕捉所有符合模式的部分,而非全局属性则只匹配首次出现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

当正则表达式有全局属性时

let s = "12mm13mm14";
let reg = /(\d)+/g;//全局
let res1, res2;
while(res1 = reg.exec(s)) {
	console.log(res1);
}
res2 = s.match(reg);
console.log(res2);
//[ '12', '2', index: 0, input: '12mm13mm14' ]
//[ '13', '3', index: 4, input: '12mm13mm14' ]
//[ '14', '4', index: 8, input: '12mm13mm14' ]
//[ '12', '13', '14' ]

当正则表达式不是全局属性时

let s = "12mm13mm14";
let reg = /(\d)+/; //非全局
let res1, res2;
res2 = s.match(reg);
console.log(res2);//[ '12', '2', index: 0, input: '12mm13mm14' ]
res2 = s.match(reg);
console.log(res2);//[ '12', '2', index: 0, input: '12mm13mm14' ]
while(res1 = reg.exec(s)) {
	console.log(res1);//陷入无限循环,[ '12', '2', index: 0, input: '12mm13mm14' ]
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值