1.const reg=/d/ 2. const reg=new RegExp(‘d’)
1.它由一个点 . 表示。用来匹配除了换行符以外的任何单个字符。 const regex = /.og/; regex.test(‘fog’); // true regex.test(‘dog’); //true
2.?匹配前面的子表达式零次或一次 (/\d?/).test(‘Do you know regex yet?’)
3.星号 * 可以使表达式匹配 0 次或多次。这相当于{0,} 贪婪量词 /[0-9]*/.test(‘hehgga’)//true
/a.*a/.test(‘greedy can be dangerous at times’) //true an be dangerous a
/a.*?a/test(‘greedy can be dangerous at times’) an be da 在星号后面加?可以变成惰性量词
4.+匹配前面的子表达式一次或多次(大于等于1次)贪婪量词 /[0-9]+/.test(‘hehgga’)//false /[0-9]+/.test(‘hehgga215’)//true
/a.+a/.test(‘greedy can be dangerous at times’) //true an be dangerous a /a.+?a/test(‘greedy can be dangerous at times’) an be da 在+后面加?可以变成惰性量词 5.^匹配输入字行首
6.$匹配输入行尾
7.字母 m 表示的多行标志 const pets = dog cat parrot and other birds; /^dog / m . t e s t ( p e t s ) ; / / t r u e / c a t /m.test(pets); // true /^cat /m.test(pets);//true/cat/m.test(pets); // true /^parrot$/m.test(pets); // false
8.\s 匹配任何不可见字符,包括空格、制表符、换页符等等。(等价于[ \f\n\r\t\v]\f匹配一个换页符,\n匹配一个换行符,\r匹配一个回车符) function containsWhitespace(string) { return /\s/.test(string); }
containsWhitespace(‘Lorem ipsum’); // true containsWhitespace(‘Lorem_ipsum’); // false
9.( )将( 和 ) 之间的表达式定义为“组”(group),并且将匹配这个表达式的字符保存到一个临时区域(一个正则表达式中最多可以保存9个),它们可以用 \1 到\9 的符号来引用。?P用来给每个分组命名 /[(?P\d+)/(?P\w+)/(?P\d+)/.([17/May/2015]) //true
10.[^xyz] 匹配未包含的任意字符 /[^pl]/.test('plain) //ain true
const regex = /.og/; 2regex.test(‘fog’); // false 3regex.test(‘dog’); //false
const regex2 = /dog./; 6regex1.test(‘dog.’); // true
1./[dfl]og/.test(‘dog’); // true 2./[dfl]og/.test(‘fog’); // true 3./[dfl]og/.test(‘log’); // true 4./[.123]/).test(‘Do you know regex yet .12356?’)// true
5.先行断言 1.(?=pattern)非获取匹配,正向肯定预查,在任何匹配pattern的字符串开始处匹配查找字符串,该匹配不需要获取供以后使用 简单说,以 xxx(?=pattern)为例,就是捕获以pattern结尾的内容xxx const expression = /x(?=y)/; expression.test(‘x’); // false expression.test(‘xy’); // true expression.test(‘xsddfdxsy’); // false expression.test(‘xsddfdxy’); // true
2.(?:pattern)非获取匹配,匹配pattern但不获取匹配结果,不进行存储供以后使用 (‘industr(?:y|ies)’ 就是一个比 ‘industry|industries’ 更简略的表达式) const expression = /x(?:y)/; expression.test(‘x’); // false expression.test(‘xy’); // true 3.(?!pattern)非获取匹配,正向否定预查,在任何不匹配pattern的字符串开始处匹配查找字符串,该匹配不需要获取供以后使用 简单说,以 xxx(?!pattern)为例,就是捕获不以pattern结尾的内容xxx const expression = /x(?!y)/; expression.test(‘x’); // true expression.test(‘xy’); // false 4(?<=pattern)非获取匹配,反向肯定预查,与正向肯定预查类似,只是方向相反 简单说,以(?<=pattern)xxx为例,就是捕获以pattern开头的内容xxx
const expression = /x(?<=y)/; expression.test(‘x’); // false expression.test(‘yx’); //false
const expression = /(?<=y)x/; expression.test(‘x’); // false expression.test(‘yx’); // true 5(?<!pattern)非获取匹配,反向否定预查,与正向否定预查类似,只是方向相反 简单说,以(?<!pattern)xxx为例,就是捕获不以pattern开头的内容xxx。
const expression = /x(?<!y)/; expression.test(‘x’); // true expression.test(‘xy’); // true
const expression = /(?<!y)x/; expression.test(‘x’); // true expression.test(‘yx’); // false
