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

匹配重复出现的子串

    方法:

  •   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

猜你喜欢

转载自www.cnblogs.com/benjaminwenfeng/p/9254232.html