- 1、改变优先级
- 2、分组引用
\2代表和第二个分组出现一模一样的内容;\1和第一个分组出现一模一样的内容;
一模一样:和对应的分组中的内容的值都要一样
var reg = /^(\w)\1(\w)\2$/;
console.log(reg.test("zzhh"));//->true,zz相同,hh相同
console.log(reg.test("zzh_"));//->false,zz相同,h_不相同
console.log(reg.exec("zzhh"));//->["zzhh", "z", "h", index: 0, input: "zzhh"]
console.log(reg.exec("0011"));//->["0011", "0", "1", index: 0, input: "0011"]
- 3、分组捕获 ->正则在捕获的时候,不仅仅把大正则匹配的内容捕获到,而且还可以把小分组匹配的内容捕获到
-
(?:) 在分组中?:的意思是只匹配不捕获
var reg = /^(\d{2})(\d{4})(\d{4})(\d{2})(\d{2})(?:\d{2})(\d)(?:\d|X|x)$/; var str = "34222419900428123x"; var ary=reg.exec(str);//["34222419900428123X", "34", "2224", "1990", "04", "28", "3", index: 0, input: "34222419900428123X"] console.log(ary); //ary[0] -> 大正则匹配的内容 //ary[1] ->第一个分组捕获的内容 //ary[2] ->第二个分组捕获的内容 //... console.log(str.match(reg));//->和exec获取的结果是一样的
var reg = /zhu(\d+)/g; var str = "zhu1234zhu3456zhu5678"; //我们用exec执行三次,每一次不仅仅把大正则匹配的获取到,而且还可以获取第一个分组匹配的内容 console.log(reg.exec(str));//->["zhu1234", "1234"...] console.log(reg.exec(str));//->["zhu3456", "3456"...] console.log(reg.exec(str));//->["zhu5678", "5678"...] //而match只能捕获大正则匹配的内容 console.log(str.match(reg));//->["zhu1234", "zhu3456", "zhu5678"]
-