正表达式匹配一个字符串内重复出现的所有子字符串

本文对比分析了JavaScript中使用match()和exec()方法进行正则表达式匹配的区别,通过实例展示了如何利用这两种方法来查找字符串中的重复子串,并解释了它们在实际应用中的不同表现。

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

匹配重复出现的子串

    方法:

  •   string引用对象.match();
  •   RegExp 对象.exec();

match()定义和用法

match() 方法可在字符串内检索指定的值,或找到一个或多个正则表达式的匹配。

该方法类似 indexOf() 和 lastIndexOf(),但是它返回指定的值,而不是字符串的位置。

1 function testForRegularFormation(){
2     var test_str = "atsgatttathtat";
3     var reg =/(?=^)at|(?=\w)at|at(?=\w)|at(?=$)/g ;
4   
5     var arr = test_str.match(reg);
6     console.log(arr);
7 }

firefox quantum 61.0 (64 位)结果:

Array(4) [ "at", "at", "at", "at" ]

 

exec()定义和用法

exec() 方法用于检索字符串中的正则表达式的匹配。

1 function testForRegularFormation(){
2     var test_str = "atsgatttathtat";
3     var reg =/(?=^)at|(?=\w)at|at(?=\w)|at(?=$)/g ;
4      var arr = reg.exec(test_str);
5     
6     console.log(arr);
7 }

 

firefox quantum 61.0 (64 位)结果:

Array [ "at" ]

 

疑惑:两个方法的使用为什么会有区别?

exec()方法当多次调用处理相同字符串时,会返回与字符串剩余的下一个子字串,返回的数组对象的属性index记录了这个子字串匹配时的索引下标,一直到返回的数组为空,则结束匹配所有子串。

 1 function testForRegularFormation(){
 2     var test_str = "atsgatttathtat";
 3     var reg =/(?=^)at|(?=\w)at|at(?=\w)|at(?=$)/g ;
 4     var arr = reg.exec(test_str);
 5     var res = new Array();
 6     console.log("arr: "+arr + "--> index :"+ arr.index); //1
 7     res.push(arr[0]);
 8     var arr = reg.exec(test_str);
 9     console.log("arr: "+arr + "--> index :"+ arr.index);//2
10     res.push(arr[0]);
11     var arr = reg.exec(test_str);
12     console.log("arr: "+arr + "--> index :"+ arr.index);//3
13     res.push(arr[0]);
14     var arr = reg.exec(test_str);
15     console.log("arr: "+arr + "--> index :"+ arr.index);//4
16     res.push(arr[0]);
17     console.log("res: "+res);
18     
19     var arr = reg.exec(test_str);
20     console.log("arr: "+arr + "--> index :"+ arr.index);//5
  
   arr = null;
   res = null;
21 }

 

 firefox quantum 61.0 (64 位)结果:

arr: at--> index :0          

arr: at--> index :4          
arr: at--> index :8            
arr: at--> index :12          
res: at,at,at,at                 
TypeError: arr is null[详细了解]

exec()方法需要多次调用,才能完成字符串的所有匹配。

参考链接:

http://www.w3school.com.cn/jsref/jsref_exec_regexp.asp

http://www.w3school.com.cn/jsref/jsref_match.asp

 

转载于:https://www.cnblogs.com/benjaminwenfeng/p/9254232.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值