字符串匹配
match方法
match方法是String构造函数原型对象上的方法 String.prototype.match
-
语法:str.match(value)
- value可以是一个字符串,也可以是一个正则表达式;
- 注:参数本质是一个正则表达式,若是传入的值为一个字符串,则会隐式的调用new RegExp(value) 将其转为正则表达式(没有g)
- value可以是一个字符串,也可以是一个正则表达式;
-
作用:检索字符串,以便找到1个或多个与value值得匹配;
-
检索过程
- 正则表达式若是添加了修饰符g—>match方法将进行
全局检索
,找到所有匹配的字符串;- 若是没有找到任何匹配的文本,返回值为
null
(非空数组!); - 若是找到匹配的文本,返回一个数组,包含每个匹配的文本(仅文本,无其他信息);
- 若是没有找到任何匹配的文本,返回值为
- 正则表达式若是没有添加修饰符g->match方法在str中执行
一次匹配
(找到即停止遍历)- 若是没有找到任何匹配的文本,返回值为null;
- 若是找到匹配文本,返回一个伪数组,包含与匹配文本相关信息;
- 0:匹配的文本;
- index:匹配文本在str中的起始下标;
- input:str值;
- 正则表达式若是添加了修饰符g—>match方法将进行
-
举例说明-字符串
-
const sstr = 'a' const str1 ='bvvm' const str2 = 'asdwfgcqd' console.log('结果1',str1.match(sstr)) //null console.log('结果2', str2.match(sstr)) // {0: "a" ,groups: undefined, index: 0 , input: "asdwfgcqd"}
-
-
举例说明-正则表达式
-
const str1 ='bvvm' const str2 = 'asdwfgcqd' const reg1 = /[awc]/ const reg2 = /[awc]/g console.log(1, str1.match(reg1)) // null console.log(2, str2.match(reg1)) // {0:'a',groups: undefined, index: 0 , input: "asdwfgcqd"} console.log(1, str1.match(reg2)) // null console.log(2, str2.match(reg2)) // ['a','w','c']
-
matchAll方法
matchAll方法是Es6新增的字符串遍历方法;
-
语法
-
str.matchAll(value)
-
value可以是一个字符串,也可以是一个正则表达式;
- 若是传入的值为一个字符串,则会隐式的调用new RegExp(value) 将其转为正则表达式(加g);
- 若是传入的值为一个正则表达式,必须带g,不然会报错;
-
-
作用:检索字符串,以便找到1个或多个与value值得匹配;
-
检索过程
- matchAll方法将进行
全局检索
,找到所有匹配的字符串; - 返回值为一个遍历器,可以通过循环遍历将匹配结果取出;
- matchAll方法将进行
-
举例说明
-
// 字符串遍历 for of let str = 'abcdeedcba' console.log(...str.matchAll(/f/g)) // 空的 const arr = [...str.matchAll('a')] console.log(arr) // [0: "a", groups: undefined, index: 0, input: "abcdeedcba", length: 1],[0: "a", groups: undefined, index: 9, input: "abcdeedcba", length: 1]
-