6. 正则 3


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
41
42
43
44
45
46
47
48
49
50
51
52
53
var reg=new RegExp(/\w\w/);
console.log(reg.exec("asdasda"));
//反向引用
var reg=new RegExp(/(\w)(\w)/);
console.log(reg.exec("asdasda"));

var reg=new RegExp(/(\w)(\w)\2\1/);
console.log(reg.exec("woow"));

var reg=new RegExp(/(\w)(\w)(\w)\2\1\2\3\2\.\w+/);
console.log(reg.exec("bilibili.com"));

//?:的作用,取消捕获
var reg=new RegExp(/(?:\w)(\w)(\w)(\w)\2\1\2\3\2\.\w+/);
console.log(reg.exec("abilibili.com"));

//正向预警(?:pattern)要匹配的字符后面必须有pattern
var reg=new RegExp(/\w+\.(?:com)/);
console.log(reg.exec("bilibili.com"));//"bilibili.com"

//修饰符g全局,m换行,i忽略大小写,s让.包含回车符号
var reg=new RegExp(/\w+\.(?!com)/);
console.log(reg.exec("bilibili.com"));//"bilibili.com"

//match方法
var s="123";
console.log(s.match(/\d/));

var s="123";
console.log(s.replace(/\d/g,9));

//$相当于反向引用
var s="123";
console.log(s.replace(/\d/g,"$1$1$1"));

//split
var s="aaaa.aaa.aaa";
console.log(s.split(/\W/));

var s="http://weichuang.com:80";
console.log(s.match(s,"(\w+):\/\/(w+)\.(w+).(w+):([\d])"));

//匹配网址
var s="http://www.weichuang.com:80";
console.log(s.match(/(\w+):\/\/(\w*)\.(\w+)\.(\w+):(\d*)/));

var s="http://www.weichuang.com:80";
var reg=/(\w+):\/\/(\w*)\.(\w+)\.(\w+):(\d*)/;
console.log(reg.exec(s));

var s="http://www.weichuang.com:80";
var reg=/(\w+|https?):\/\/(\w*)\.(\w+)\.(\w+):(\d*)/;
console.log(reg.exec(s));
1
2
//子表达式(),有捕获的作用,返回的数组,索引0对应所有返回值,其余从1开始逐渐递增

1

1

1

1

1

1

1

1

1

1

支持正则表达式的方法match,search,replace,split


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