Javascript的有状态正则表达式

本文探讨了JavaScript中正则表达式的特性,包括其有状态的性质、使用test方法提高搜索效率的方法,以及贪婪与非贪婪匹配的区别。通过具体示例展示了如何利用这些特性进行文本处理。

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

Javascript的正则表达式是有状态的!


var res, text = "name leo1 leo2 leo3",
    regexp = /leo(\d)/g;


console.log("regexp.lastIndex:", regexp.lastIndex);
while (res = regexp.exec(text)) {
    console.log("regexp.lastIndex:", regexp.lastIndex,
        "index:", res.index,
        "res[0]:", res[0],
        "res[1]:", res[1]);
}
console.log("regexp.lastIndex:", regexp.lastIndex);
结果:

regexp.lastIndex: 0
regexp.lastIndex: 9 index: 5 res[0]: leo1 res[1]: 1
regexp.lastIndex: 14 index: 10 res[0]: leo2 res[1]: 2
regexp.lastIndex: 19 index: 15 res[0]: leo3 res[1]: 3
regexp.lastIndex: 0
可以用test 代替 exec做判断,提高效率。

test 要比 exec 快,所以代码修改如下:


var res, text = "name leo1 leo2 leo3",
    regexp = /leo(\d)/g,lastIndex = regexp.lastIndex;


console.log("regexp.lastIndex:", regexp.lastIndex);
while (regexp.test(text)) {
    regexp.lastIndex = lastIndex;
    res = regexp.exec(text)
    console.log("regexp.lastIndex:", regexp.lastIndex,
        "index:", res.index,
        "res[0]:", res[0],
        "res[1]:", res[1]);
    lastIndex = regexp.lastIndex;
}
console.log("regexp.lastIndex:", regexp.lastIndex);

贪图与不贪图匹配

var text = "jsera net jsera net jsera net",
    greedyRegexp = /jsera.*net/g,
    nonGreedyRegexp = /jsera.*?net/g;

console.log(text.match(greedyRegexp));
console.log(text.match(nonGreedyRegexp));
结果

[ 'jsera net jsera net jsera net' ]
[ 'jsera net', 'jsera net', 'jsera net' ]




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值