正则:分组

2017-07-29  本文已影响0人  gaoqizhuhui

正则分组作用:

1、改变优先级:
2、分组引用

var reg= /^(\w)\1(\w)\2$/;  //-->\2代表和第二个分组出现一模一样(值都要一样)的内容;\1代表和第一个分组出现一模一样的内容
console.log(reg.test("hhaa"));   //--->true
console.log(reg.test("h1a_"));  //---->false

3、分组捕获:
正则在捕获的时候,不仅把大正则匹配的内容捕获到,而且还可以把小分组匹配的内容捕获到。eg:身份证号码正则捕获

var reg=/^(\d{2})(\d{4})(\d{4})(\d{2})(\d{2})(\d{2})(\d)(\d|X)$/;
var str="123456199210261521";
console.log(reg.exec(str));
//ary=["123456199210261521","12","3456","1992","10","26","15","2","1",index:0,input:"123456199210261521"] 
//ary[0]-->大正则匹配内容
//ary[1]--->第一个分组捕获的内容。。。

console.log(str.match(reg));  //--->和exec获取的结果是一样的

可以只捕获到自己想要的内容,不需要全都捕获。(?:)--->在分组中?:的意思是只匹配不捕获
var reg=/^(\d{2})(\d{4})(\d{4})(\d{2})(\d{2})(?:\d{2})(\d)(?:\d|X)$/;

match与exec捕获区别:

var reg=/haha(\d+)/g;
var str="haha1234haha3456haha5678";
console.log(reg.exec(str));  //--->["haha1234","1234"...]
console.log(reg.exec(str));  //--->["haha3456","3456"...]
console.log(reg.exec(str));  //--->["haha5678","5678"...]

console.log(str.match(reg));  //--->["haha1234","haha3456","haha5678"]

用exec执行三次,每一次不仅把大正则匹配的内容获取到,而且还可以获取第一个分组匹配的内容。

而match只能捕获到大正则匹配的内容

上一篇下一篇

猜你喜欢

热点阅读