5. 正则 2


用法

  1. 可用于字符串匹配
  2. 效率高

写法

  1. ```javascript
    var reg=/abc/;
    var str=”abcdefg”;
    var result=reg.exec(str);//execute执行
    console.log(result);
    1
    2
    2. ```javascript
    var reg=new RegExp('abc');

{}的作用

匹配数量

1
2
var reg=new RegExp('c{2}','g');
console.log(reg.exec("cccccccc"));

匹配手机号

1
2
var reg=new RegExp('\\d{3}[0123456789]{8}','g');
console.log(reg.exec("15331860803"));

c{m,n}匹配连续的m到n个(包含m,n)c,如果同时符合,就匹配尽可能多的那个

1
2
var reg=/c{3,4}/;
console.log(reg.exec("ccccccc"));

c{m,}匹配大于等于m个c,尽可能找多的

1
2
var reg=/c{3,}/;
console.log(reg.exec("cccccccaaaaa"));

[]作用

  1. ```javascript
    //划分一个规则集合
    var reg=/[123,]/;
    console.log(reg.exec(“123123,12323”));
    1
    2
    3
    4
    2. ```javascript
    //可以用-来在区间定义多个条件
    var reg=/[a-z]/;
    console.log(reg.exec('Ah'));

*,+,?

*是匹配0个或多个,相当于{0,}

1
2
var reg=/c*/;
console.log(reg.exec('cccc'));

+是匹配1个或多个,相当于{1,}

1
2
var reg=/c+/;
console.log(reg.exec('ccccaaa'));

?是匹配0个或1个,相当于{0,1}

1
2
var reg=/c?/;
console.log(reg.exec('ccccaaa'));

**+,默认贪婪,匹配数量尽可能多,非贪婪模式需要加一个?*

1
2
var reg=/c*?/;
console.log(reg.exec('ccccaaa'));//""

^c匹配以c为开始

1
2
3
var reg=/^c/;
console.log(reg.exec('ccccaaa'));//"c"
console.log(reg.exec('accccaaa'));//null

c$匹配以c为结尾

1
2
3
var reg=/c$/;
console.log(reg.exec('cccc'));//"c"
console.log(reg.exec('旺仔小c'));//"c"

.匹配任意字符,只有一个

1
2
3
4
5
6
7
8
var reg=/./;
console.log(reg.exec('cccc'));//"c"

var reg=/.+/;
console.log(reg.exec('你好cccc'));//"你好cccc"

var reg=/.{2,3}/;
console.log(reg.exec('你好cccc'));//"你好c"

|或者,优先级高于^

\b是边界的意思,但是遇到中文或者特殊符号会有问题

1
2
3
4
5
6
7
8
9
10
11
12
13
14
var reg=/\bc/;
console.log(reg.exec('asd cccc'));//"c"

var reg=/\bc/;
console.log(reg.exec('asdcccc'));//null

var reg=/\bc/;
console.log(reg.exec('asdc'));//null

var reg=/\bc/;
console.log(reg.exec('你好c'));//"c"

var reg=/\bc/;
console.log(reg.exec('c c'));//"c"

Author: pkq
Reprint policy: All articles in this blog are used except for special statements CC BY 4.0 reprint policy. If reproduced, please indicate source pkq !
  TOC