js中的正则表达式

匹配方法:

String.prototype.match(Regexp)
//用正则表达式匹配字符串,默认返回首次匹配字符串,若Regexp带有g,则返回数组,包含所有匹配的字符串
String.prototype.test(Regexp)
//返回true或false
RegExp.prototype.exec(String) 
//若加g,依然返回单个匹配字符串,但如果正则存储在变量中,那么exec将带有记忆,如:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
> /h(.*?)\b/g.exec('hello hell')
[ 'hello',
'ello',
index: 0,
input: 'hello hell' ]
> /h(.*?)\b/g.exec('hello hell')
[ 'hello',
'ello',
index: 0,
input: 'hello hell' ]
> var re = /h(.*?)\b/g;
undefined
> re.exec('hello hell')
[ 'hello',
'ello',
index: 0,
input: 'hello hell' ]
> re.exec('hello hell')
[ 'hell',
'ell',
index: 6,
input: 'hello hell' ]
>

所以一般来讲,match会比较方便一点。

正则表达式后的三个flag:

  • i:不区分大小写
  • g:匹配多个
  • m:^$可以匹配每一行的开头和结尾

常用规则:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
//字符转义
var Test1='.. ,,';
var re=/(\.){2}/g
console.log(Test1.match(re));//[ '..' ]
//重复
var Test2='131-2222 1212-1111 222-3333';
var re=/\b\d{3}-\d{4}/g;
console.log(Test2.match(re));//[ '131-2222', '222-3333' ]
//分支条件
var Test3='abba accb adcc abcd aeea';
var re=/\ba[a-zA-Z]*a\b|\ba[a-zA-Z]*b\b/g;
console.log(Test3.match(re));//[ 'abba', 'accb', 'aeea' ]
//分组
var Test4='gogogo out gogo'
var re=/(go)+/g;
console.log(Test4.match(re));//[ 'gogogo', 'gogo' ]
//反义
var Test5='a>1 a<5 a=6 a>0 a=7';
var re=/a[^=]\d+/g;
console.log(Test5.match(re));//[ 'a>1', 'a<5', 'a>0' ]
//后向引用
var Test6='g g g g g kitty ';
var re=/\b(\w)\b\s+\1\b/g;
console.log(Test6.match(re));//[ 'g g', 'g g' ]
//零宽度正预测先行断言(?=exp)
var Test7='singing,dancing,fucked';
var re=/\b\w+(?=ing\b)/g;
console.log(Test7.match(re));//[ 'sing', 'danc' ]
//零宽度负预测先行断言(?!exp)
var Test8='apple ap123 app11ap';
var re=/\bap(?!\d)[a-zA-Z]*\b/g;
console.log(Test8.match(re));//[ 'apple' ]

在JS中,对于四种零宽断言,只支持 零宽度正预测先行断言零宽度负预测先行断言 这两种。