js 正则表达式分组
正则表达式分组:通俗的就是正则表达式中()包起来的内容表示一个分组
例如:
1 var reg = /^(\d{2})$/; 2 var asd = reg.test('12'); 3 console.log(asd);
结果是 true;
1、利用正则表达式优雅的表达重复的字符串
1 var reg2 = /^(SD)\d{4}(-\d{4}){3}$/; 2 console.log(reg2.test('SD0214-0000-0000-0000'))
结果 true;
例如:/^(ha){3}$/ 等同于 /^hahaha$/
2 、多个候选表达式
1 var reg3 = /^I come from (hunan|hubei|zhejiang)$/; 2 console.log(reg3.test('I come from hunan'));
3、分组的分类:捕获型();非捕获型(?:);正向前瞻性(?=);反向前瞻性(?!)
1 // 1、获取 2 var reg4 = /^(\d{4})-(\d{2})-(\d{2})$/ 3 var data = '2018-10-17'; 4 reg4.test(data); 5 console.log(RegExp.$1); // 输出 2018 6 console.log(RegExp.$2); // 输出 10 7 console.log(RegExp.$3); // 输出 17 8 9 // 2、结合replace方法做字符串自定义转换 10 var date2 = '2018/04/18'; 11 var reg5 =/^(\d{4})\/(\d{2})\/(\d{2})$/; 12 var dateStr = date2.replace(reg5, '$1-$2-$3') //"2018-04-18"; 13 console.log(dateStr); 14 15 // 3、反向引用 16 var reg6 = /^(\w{3}) is \1$/; 17 console.log(reg6.test('kid is kid')); // true 18 console.log(reg6.test('kid is dik')); // false
19 // 如果越界或者编号不存在,则被解析为普通的表达式 20 var reg7 = /^(\w{3}) is \6$/; 21 console.log(reg7.test('kid is \6')); // true 22 console.log(reg7.test('kid is kid')); // false 23 24 // 4、非捕获型分组 25 var reg8 = /^(?:\d{4})-(\d{2})-(\d{2})$/; 26 var date3 = '2018-10-18'; 27 reg8.test(date3); 28 console.log(RegExp.$1); 29 console.log(RegExp.$2); 30 31 // 5、正向与反向前瞻性分组; 正向,站在原地往前看,如果前方是指定的东西就返回true,否则返回false 32 33 var reg9 = /^kid is a (?=doubi)$/; 34 console.log(reg9.test('kid is a doubi')); // true 35 console.log(reg9.test('kid is a shabi'));// false