一.基本形式
(1).声明方式
var p2 = new RegExp('at','gim') 不建议使用这种方式
var p1 = /\.at/
var p2 = new TegExp('\\.at')因为在字符串中需要转译
console.log(/ab /.test('ab'));
二.元字符
(1).\转义符
log(/1+1/.test('1+1')); //false
log(/1\+1/.test('1+1'));//true
log(/]/gim.test(']'))//false
log(/\]/gim.test(']'))//true
log(/\\a/gim.test('a'));//false
log(/\\a/gim.test('\a'));//false
log(/\\a/gim.test('\\a'));//true
(2).[]范围
log(/[0-9]/)
log(/[5678901234]/)两者等价,但是第二种是无序的,但是第一种是有序的
log(/[9-0]/.test(1))//这样会报错
log(/[0-9A-Za-z]/.test('1'))
log(/[0-9A-Za-z]/.test('A'))
log(/[0-9A-Za-z]/.test('a'))
log(/[0-9a-zA-Z]/.test('a'))
log(/[0-9a-zA-Z]/.test('A'))
log(/[0-9a-zA-Z]/.test('1'))
log(/[1-34-67-9]/.test('5'))
log(/[1-34-67-9]/.test('1'))
log(/[1-34-67-9]/.test('7'))
log(/[1-34-67-9]/.test('8'))
log(/[1-34-67-9]/.test('3'))
log(/[-]/.test('-'))//true
(3).[^]范围取反
log(/[^a-z]/.test('A'))//TRUE
LOG(/[^a]/.test('b'))//true
(4).范围的简写
(5).次数
log(/[0-9][0-9][0-9]/);
log(/\d\d\d/)
log(/\d{6}/)
log(/\d{6}/.exec(123456789));
log(/\d{6,}/.exec(123456789));
(6).次数为一次或0次的缩写
(7).非贪婪模式
log(/a+?/.exec('aaaaa')) //只能匹配到一个a
.test是会返回true的,因为都匹配上了,匹配几位不重要
log(/<script>[\s\S]*?<\/script>/.exec('<script>var a =1<\/script>'))
8.()子表达式
log(/\w\d{3,6}/.exec('a123')) //a123
log(/(\w\d){3,6}/.exec('a1b2c3'))//a1b2c3
log(/(\d{4})-(\d{1,2})-(\d{1,2})/exec('2020-7-17'))//
0:2020-7-17
1:2020
2:7
3:17
log(RegExp.$1);//2020
log(RegExp.$2);//7
log(RegExp.$3);//17
//没有$0
(9).非捕获
let arr1=/(\d\d){1,2}-(\d\d){1,2}-(\d{4})/.exec('1988-1999-2020')
log(arr1[1])//88
log(arr1[2])//99
log(arr1[3])//2020
let arr1 =/(?:\d\d){1,2}-(?:d\d){1,2}-(\d{4})/.exec('1988-1999-2020')
log(arr1[1])//2020
log(arr1[2])//un
log(arr1[3])//un
log(/(\d\d){1,2}/.exec('2014')) //0 :2014 1:14
log(/(\d\d){1,2}?/.exec('2014'))//0: 20 1:20
(10).反向引用
log(/\w\w/.exec('ab'))//ab
log(/(\w)\1/.exec('aa'))//0:aa 1:a
log(/<([^<>]+)>.*?<\/\1>/.exec('<ab>13sdf</ab>'))//
0:<ab>13sdf</ab>
1:ab