js正则表达式

前言

正则表达式(Regular Expression,在代码中常简写为regex、regexp或RE)使用单个字符串来描述、匹配一系列符合某个句法规则的字符串搜索模式。

正则表达式是由一个字符序列形成的搜索模式。

当你在文本中搜索数据时,你可以用搜索模式来描述你要查询的内容。

正则表达式可以是一个简单的字符,或一个更复杂的模式。

正则表达式可用于所有文本搜索和文本替换的操作。

一、正则表达式的创建

1、字面量(直接量)

语法:

var reg = /正则表达式/模式修饰符;

比如:

var reg = /hello/g

2、构造函数

语法:

//内部传入参数需要添加引号
var reg =new RegExp("正则表达式","模式修饰符")

比如:

var reg = new RegExp("hello","g")

模式修饰符:

i:ignoreCase,匹配时忽视大小写
m:multiline,多行匹配
g:global,全局匹配

二、正则表达式实例方法

1、exec 方法

用来匹配字符串中符合正则表达式的字符串:如果匹配到,返回值是一个数组,否则返回null

返回的数组内容:
[匹配的内容,index: 在str中匹配的起始位置,input: 参数字符串,groups: undefined]

var str = 'hello html hello css hello js'
//全局匹配 hello
var reg = /hello/g
//全局匹配每次调用exec方法都会向后寻找,寻找完最后一个时,又会重头开始
console.log(reg.exec(str)); //['hello', index: 0, input: 'hello html hello css hello js', groups: undefined]
console.log(reg.exec(str)); //['hello', index: 11, input: 'hello html hello css hello js', groups: undefined]
console.log(reg.exec(str)); //['hello', index: 21, input: 'hello html hello css hello js', groups: undefined]
console.log(reg.exec(str)); //null
console.log(reg.exec(str)); //['hello', index: 0, input: 'hello html hello css hello js', groups: undefined]


//因此,对于全局匹配,我们可以使用循环进行输出
while(true){
  var res = reg.exec(str)
  //当返回值为null时,跳出循环
  if(!res){
    break
  }
  console.log(res);
}


//如果不使用全局匹配,每次都会从头开始找
var reg1 = /hello/
console.log(reg1.exec(str)); //['hello', index: 0, input: 'hello html hello css hello js', groups: undefined]
console.log(reg1.exec(str)); //['hello', index: 0, input: 'hello html hello css hello js', groups: undefined]
console.log(reg1.exec(str)); //['hello', index: 0, input: 'hello html hello css hello js', groups: undefined]

2、test 方法

用来测试待检测的字符串中是否有可以匹配到正则表达式的字符串,如果有返回true,否则返回false

var str = 'hello html hello css hello js'
var reg = /hello/g
console.log(reg.test(str)); // true
console.log(reg.test(str)); // true
console.log(reg.test(str)); // true
console.log(reg.test(str)); // false
console.log(reg.test(str)); // true

❤ 总结:
1、如果正则表达式中有修饰符"g",这时,在正则表达式的实例reg中会维护lastIndex属性,记录下一次开始的位置,当第二次执行exec的时候,从lastIndex开始检索。
2、如果正则表达式中没有修饰符"g",不会维护lastIndex属性,每次执行从开始位置检索

3、toString 和 toLocaleString 方法

toString:把正则表达式的内容转化成字面量形式字符串
toLocaleString:把正则表达式的内容转化成有本地特色的字符串(JS中没效果)

var reg = /hello/g
console.log(reg.toString()); // /hello/g
console.log(reg.toLocaleString()); // /hello/g

4、valueOf 方法

返回正则表达式本身

var reg = /hello/g
console.log(reg.valueOf()); // /hello/g

三、正则表达式实例属性

1、lastIndex

  • 当没设置全局匹配时,该属性值始终为0
  • 设置了全局匹配时,每执行一次exec/test来匹配,lastIndex就会移向匹配到的字符串的下一个位置,当指向的位置后没有可以再次匹配的字符串时,下一次执行exec返回null,test执行返回false,然后lastIndex归零,从字符串的开头重新匹配一轮
  • 可以理解成,每次正则查找的起点就是lastIndex
var str = 'hello html hello css hello js'
// 没有开启全局匹配
var reg1 = /hello/
// 开启全局匹配模式
var reg2 = /hello/g

console.log(reg1.lastIndex); // 0
console.log(reg1.exec(str)); // ['hello', index: 0, input: 'hello html hello css hello js', groups: undefined]
console.log(reg1.lastIndex); // 0

console.log(reg1.lastIndex); // 0
console.log(reg1.exec(str)); // ['hello', index: 0, input: 'hello html hello css hello js', groups: undefined]
console.log(reg1.lastIndex); // 0

console.log(reg2.lastIndex); // 0
console.log(reg2.exec(str)); // ['hello', index: 0, input: 'hello html hello css hello js', groups: undefined]
console.log(reg2.lastIndex); // 5

console.log(reg2.lastIndex); // 5
console.log(reg2.exec(str)); // ['hello', index: 11, input: 'hello html hello css hello js', groups: undefined]
console.log(reg2.lastIndex); // 16

console.log(reg2.lastIndex); // 16
console.log(reg2.exec(str)); // ['hello', index: 21, input: 'hello html hello css hello js', groups: undefined]
console.log(reg2.lastIndex); // 26

console.log(reg2.lastIndex); // 26
console.log(reg2.exec(str)); // null
console.log(reg2.lastIndex); // 0

2、ignoreCase、global、multiline

判断正则表达式中是否有忽略大小写、全局匹配、多行匹配三个模式修饰符

var reg = /hello/igm;
console.log(reg.ignoreCase); //true
console.log(reg.global); //true
console.log(reg.multiline);  //true

3、source

返回字面量形式的正则表达式(类似于toString)

var reg = /hello/g
console.log(reg.source); // 'hello' 

四、正则表达式语法

1、直接量字符

正则表达式中的所有字母和数字都是按照字面含义进行匹配的,Javascript正则表达式语法也支持非字母的字符匹配,这些字符需要通过反斜线\作为前缀进行转义。

字符匹配
字母和数字字符自身
\oNull字符
\t制表符
\n换行符
\v垂直制表符
\f换页符
\r回车符
var reg = /\n/g
console.log(reg.test('hello \n world')); // true

2、字符集合

一个字符集合,也叫字符组。匹配集合中的任意一个字符。你可以使用连字符-指定一个范围。

方括号[]

方括号[]用于查找某个范围内的字符:

[abc] 查找方括号之间的任何字符

var reg = /[abc]/ 
// 只要包含有a 或者 包含有b 或者包含有c 都返回为true
console.log(reg.test('123')); //false
console.log(reg.test('123a')); //true
console.log(reg.test('123b')); //true
console.log(reg.test('123c')); //true
console.log(reg.test('abc')); //true

[0-9] 查找任何从0至9的数字
[a-z] 查找任何从a至z的小写字母
[A-Z] 查找任何从A至Z的大写字母

var reg = /[0-9a-z]/ 
// 只要包含有 0~9,a~z 里面的其中之一 都返回为true
console.log(reg.test('1AAAAA')); //true
console.log(reg.test('AAAAa')); //true
console.log(reg.test('AAAA!')); //false

[^abc] 一个反义或补充字符集,也叫反义字符组。也就是说,它匹配任意不在括号内的字符。你也可以通过使用连字符 - 指定一个范围内的字符。

var reg = /[^abc]/  
// 只要有除了a、b、c以外的字符存在 都返回为true
console.log(reg.test('123a')); //true
console.log(reg.test('b')); //false
console.log(reg.test('abc')); //false
console.log(reg.test('123!')); //true

注意:^写在[]里面是反义字符组,写在[]外面是边界符。

3、边界符

^ 匹配输入开始。表示匹配行首的文本(以谁开始)。如果多行(multiline)标志被设为 true,该字符也会匹配一个断行(line break)符后的开始处。

$ 匹配输入结尾。表示匹配行尾的文本(以谁结束)。如果多行(multiline)标志被设为 true,该字符也会匹配一个断行(line break)符前的结尾处。

如果 ^$ 在一起,表示必须是精确匹配。

// 只要包含有abc这个字符串返回的都是true
var reg1 = /abc/; 
console.log(reg1.test('abc'));  //true
console.log(reg1.test('abcd')); //true
console.log(reg1.test('aabcd'));//true
console.log('---------------------------');

// 必须是以abc开头的字符串才会满足
var reg2 = /^abc/;
console.log(reg2.test('abc')); // true
console.log(reg2.test('abcd')); // true
console.log(reg2.test('aabcd')); // false
console.log('---------------------------');

// 必须是以abc结尾的字符串才会满足
var reg3 = /abc$/;
console.log(reg3.test('abc')); // true
console.log(reg3.test('qweabc')); // true
console.log(reg3.test('aabcd')); // false
console.log('---------------------------');

// 精确匹配 要求必须是 abc字符串才符合规范
var reg4 = /^abc$/;
console.log(reg4.test('abc')); // true
console.log(reg4.test('abcd')); // false
console.log(reg4.test('aabcd')); // false
console.log(reg4.test('abcabc')); // false

\b 匹配一个零宽单词边界(zero-width word boundary),表示一个单词的边界。

\B 匹配一个零宽非单词边界(zero-width non-word boundary),与\b相反。

❤ javascript中正则表达式单词是指由\w[a-zA-Z0-9_]组成的字符串,单词的首尾就是单词边界,除了单词边界以外的就是非单词边界。

var str = 'hello+html javascript!css=123abc'
//上述字符串的单词边界用竖线表示出来就是:|hello|+|html| |javascript|!|css|=|123abc|
var reg1 = /\b\+\b/ // \ 可以将特殊字符转义成普通字符, + 属于特殊字符
console.log(reg1.test(str)); // true
var reg2 = /\b \b/
console.log(reg2.test(str)); // true
var reg3 = /\B23ab\B/
console.log(reg3.test(str)); // true
var reg4 = /\b123a\B/
console.log(reg4.test(str)); // true
var reg4 = /\bel\b/
console.log(reg4.test(str)); // false

字符集合与^$一起使用:

// 三选一 只有是a 或者是 b  或者是c 这三个字母才返回 true
var reg1 = /^[abc]$/; 
console.log(reg1.test('aa'));//false
console.log(reg1.test('a'));//true
console.log(reg1.test('b'));//true
console.log(reg1.test('c'));//true
console.log(reg1.test('abc'));//false
//26个英文字母任何一个字母 都返回 true
var reg2 = /^[a-z]$/ 
console.log(reg2.test('a'));//true
console.log(reg2.test('z'));//true
console.log(reg2.test('A'));//false
//字符组合
// 26个英文字母(大写和小写都可以)任何一个字母 都返回 true,0~9任何一个数字 都返回 true
var reg3 = /^[a-zA-Z0-9]$/; 
//取反 方括号内部加上 ^ 表示取反,只要包含方括号内的字符,都返回 false 。
var reg4 = /^[^a-zA-Z0-9]$/;
console.log(reg4.test('a'));//false
console.log(reg4.test('B'));//false
console.log(reg4.test(1));//false
console.log(reg4.test('!'));//true

4、字符类

字符类含义
.匹配除换行符\n和回车符之外的任何单个字符,等效于[^\n\r]
\d匹配一个数字字符,等效于[0-9]
\D[^0-9]
\w匹配包括下划线的任何单个字符,包括A-Z,a-z,0-9和下划线 _,等效于 [_a-zA-Z0-9]
\W[^a-zA-Z0-9_]
\s匹配任何Unicode空白字符,包括空格、制表符、换页符等,等效于[\f\t\n\r]
\S[^\f\t\n\r]
结合英文原意记忆:
d ==> digit(数字)
s ==> space(空白)
w ==> word(单词)

5、数量词

字符含义
*>=0次
+≥1 次
0或1次
{n}n 次
{n,}≥n 次
{n,m}n到m 次

X* 匹配前面的模式X 0 次或多次,等价于{0,}

// 允许 a 出现0次或多次
var reg = new RegExp(/^a*$/);
console.log(reg.test("aaaa")); // true
console.log(reg.test("")); // true

X+ 匹配前面的模式X 1次或多次,等价于 {1,}

// 允许a出现1次或多次
var reg = new RegExp(/^a+$/);
console.log(reg.test("aaaa")); // true
console.log(reg.test("")); // false

X? 匹配前面的模式X 0次或1次,等价于{0,1}

// 允许a出现0次或1次
var reg = new RegExp(/^a?$/);
console.log(reg.test("aaaa")); // false
console.log(reg.test("")); // true
console.log(reg.test("a")); // true

X{n} n为非负整数,前面的模式 X 重复出现 n 次时匹配

// {3} 允许重复3次
var reg = new RegExp(/^a{3}$/);
console.log(reg.test("aaa")); // true
console.log(reg.test("")); // false
console.log(reg.test("aa")); // false

X{n,} n为非负整数,前面的模式X重复出现至少 n 次时匹配

// {3,} 允许重复出现3次或3次以上多次
var reg = new RegExp(/^a{3,}$/);
console.log(reg.test("aaa")); // true
console.log(reg.test("")); // false
console.log(reg.test("aaaaaaaaa")); // true

X{n,m} n和m为非负整数,前面的模式X重复出现至少 n 次,至多 m 次时匹配

//  {3,6} 允许重复出现3次-6次之间,也就是>=3且<=6
var reg = new RegExp(/^a{3,6}$/);
console.log(reg.test("aaa")); // true
console.log(reg.test("aaaa")); // true
console.log(reg.test("aaaaaa")); // true
console.log(reg.test("aaaaaaaaa")); // false

案例:
1、匹配QQ号
要求:不能以数字0开始,只能由数字组成,长度为5-11位

//不能以数字0开始,只能由数字组成,长度为5-11位
//除去开头,那么就剩下4-10位
var reg = /^[1-9]\d{4,10}$/
console.log(reg.test('123456')); //true
console.log(reg.test('0123456')); //false
console.log(reg.test('123567b')); //false

2、匹配身份证号
要求:不能以数字0开头,只能由数字组成,最后一位可能是x,X,数字

//不能以数字0开头,只能由数字组成,最后一位可能是x,X,数字,一共18位
//除去开头和结尾,就剩下16位
var reg = /^[1-9]\d{16}[xX0-9]$/
console.log(reg.test('43833712345432534x')); //true
console.log(reg.test('038337123454325341')); //false
console.log(reg.test('338337123454325340')); //true
console.log(reg.test('13833712345432534b')); //false

5.1 重复方式

贪婪模式

尽可能多的匹配(首先取最多可匹配的数量为一组进行匹配),当匹配剩余的字符串,还会继续尝试新的匹配,直到匹配不到为止,为默认模式

// 对字符串"1234567890",匹配其中的数字3-6次:\d{3,6},先匹配数字出现6次的字符串(123456),
// 然后再从剩余字符串(7890)中匹配出现数字3次的情况,剩余字符若没有出现数字3次则停止匹配.
var str = "123456789";
var reg = /\d{3,6}/g;
console.log(reg.exec(str)); //[ '123456', index: 0, input: '12345678', groups: undefined ]
console.log(reg.exec(str)); // [ '789', index: 6, input: '123456789', groups: undefined ]
console.log(reg.exec(str)); // null
非贪婪模式

尽可能少的匹配(每次取最少匹配的数量为一组进行匹配),直到匹配不到为止。

使用方法:在量词后加上

// 对字符串"1234567890",匹配其中的数字3-6次:\d{3,6},先匹配数字出现3次的字符串(123),
// 然后再从剩余字符串(4567890)中匹配出现数字3次的情况,剩余字符若没有出现数字3次则停止匹配.
var str = "1234567890";
var reg = /\d{3,6}?/g;
console.log(reg.exec(str)); //[ '123', index: 0, input: '123456789', groups: undefined ]
console.log(reg.exec(str)); // [ '456', index: 3, input: '123456789', groups: undefined ]
console.log(reg.exec(str)); // [ '789', index: 6, input: '123456789', groups: undefined ]
console.log(reg.exec(str)); // null

6、选择,分组,引用

6.1 选择

字符 | 用于分隔供选择的字符,用来匹配选择项中的任意一个。
(可以理解为 “或” 逻辑)

var reg = /html|css|js|\d/
console.log(reg.exec('hello1 html css js')); // 1

6.2 分组

有圆括号 () 包裹的一个小整体称为分组。

var reg = /hellohellohello/

//上述正则表达式可以写成:
var reg = /(hello){3}/
候选

一个分组中,可以有多个候选表达式,用 | 分隔:

var reg = /I Like (basketball|football|table tennis)/
console.log(reg.test('I Like basketball')); //true
console.log(reg.test('I Like football')); //true
console.log(reg.test('I Like table tennis')); //true
捕获与引用

被正则表达式匹配(捕获)到的字符串会被暂存起来。其中,由分组捕获的串会从1开始编号,于是我们可以引用这些串:

var reg = /(\d{4})-(\d{2})-(\d{2})/
var date = '2021-08-29'
reg.test(date)
// 捕获之前要先test/exec
console.log(RegExp.$1); //2021
console.log(RegExp.$2); //08
console.log(RegExp.$3); //29

嵌套分组的捕获:
如果碰到类似/((it) is (a (apple)))/的嵌套分组,捕获的顺序是什么?
规则:以左括号出现的顺序进行捕获。

var reg = /((it) is (a (apple)))/
var str = "it is a apple"
reg.test(str) // true
console.log(RegExp.$1); //it is a apple
console.log(RegExp.$2); //it
console.log(RegExp.$3); //a apple
console.log(RegExp.$4); //apple

6.3 引用

正则表达式里也能进行引用,这称为反向引用:

\1引用了第一个被分组所捕获的串,换言之,表达式是动态决定的。

// \1引用了第一个被分组所捕获的串,可以理解成/(\w{3}) is (\w{3})/,但是两者不完全相同
var reg = /(\w{3}) is \1/
//由于是引用的,所以两个必须完全相同
console.log(reg.test('kid is kid')); // true
console.log(reg.test('dik is dik')); // true
console.log(reg.test('kid is dik')); // false
console.log(reg.test('dik is kid')); // false

//这里两个分组是独立的
var reg = /(\w{3}) is (\w{3})/
console.log(reg.test('kid is kid')); // true
console.log(reg.test('dik is dik')); // true
console.log(reg.test('kid is dik')); // true
console.log(reg.test('dik is kid')); // true

注意,如果编号越界了,则会被当成普通的表达式:

var reg = /(\w{3}) is \6/;
console.log(reg.test( 'kid is kid' )); // false
console.log(reg.test( 'kid is \6' ));  // true

7、前瞻表达式

在正则表达式当中有个东西叫做前瞻,有的管它叫零宽断言:

表达式名称描述
(?=exp)正向前瞻匹配后面满足表达式exp的位置
(?!exp)负向前瞻匹配后面不满足表达式exp的位置

由于 JS 原生不支持后瞻,所以这里就不研究它了。我们来看看前瞻的作用:

正向前瞻:

var str = 'HelloHtmlHappy';
// H 后面一定要匹配 t
var reg = /H(?=t)/g;
console.log(reg.exec(str)); //[ 'H', index: 5, input: 'HelloHtmlHappy', groups: undefined ]
console.log(reg.exec(str)); //null

负向前瞻:

var str = 'HelloHtmlHappy';
// H 后面一定不要匹配 t
var reg = /H(?!t)/g;
console.log(reg.exec(str)); //[ 'H', index: 0, input: 'HelloHtmlHappy', groups: undefined ]
console.log(reg.exec(str)); //[ 'H', index: 9, input: 'HelloHtmlHappy', groups: undefined ]
console.log(reg.exec(str)); //null

五、正则表达式结合String的方法使用

search

查找字符串中是否有匹配正则的字符串,有则返回字符串第一次出现时的位置,无则返回null

正则中无论是否有全局匹配都不会影响返回结果

var str = 'hello world hello';
var reg = /hello/;
var reg2 = /hello/g;
console.log(str.search(reg)); //返回 0
console.log(str.search(reg2));//返回 0

match

匹配字符串中符合正则表达式的字符串,并返回该字符串的一个数组,其中包括字符串内容位置

如果正则设置全局匹配,则一次性返回所有符合正则表达式的字符串数组

如果其中添加了分组,返回符合要求的字符串以及分组的一个数组,但如果同时开启全局匹配则不会在数组中添加分组内容

var str = 'hello world hello';
var reg1 = /hello/;
var reg2 = /hello/g;
var reg3 = /(he)llo/;
var reg4 = /(he)llo/g;

// 匹配字符串中符合正则表达式的字符串,并返回该字符串的一个数组,其中包括字符串内容、位置
console.log(str.match(reg1)); // [ 'hello', index: 0, input: 'hello world hello', groups: undefined ]

// 如果正则设置全局匹配,则一次性返回所有符合正则表达式的字符串数组
console.log(str.match(reg2)); // [ 'hello', 'hello' ]

// 如果其中添加了分组,返回符合要求的字符串以及分组的一个数组
console.log(str.match(reg3)); // ['hello','he',index: 0, input: 'hello world hello', groups: undefined]

// 如果同时开启全局匹配则不会在数组中添加分组内容
console.log(str.match(reg4)); // [ 'hello', 'hello' ]

split

以某种形式分割字符串

// 以某种形式分割字符串 split()
var str = "yezi134wangwu156lisi12zhangsan";
// 当数字出现一次或多次时
var reg = /\d+/;
var result = str.split(reg);
console.log(result); // [ 'yezi', 'wangwu', 'lisi', 'zhangsan' ]

replace

// 满足正则表达式条件的内容将被替换
var str = 'javascript'
// 如果开启全局模式 则替换所有满足条件的字符
var reg = /java/;
// replace(正则表达式, 要替换的内容)
var result = str.replace(reg, '1111');
console.log(result); //1111script
console.log(str); //javascript
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值