正则表达式

114 阅读2分钟

一、字符串方法

字符串对象有4个方法可以使用正则表达式:match、replace、search、split

1、match

如果没有匹配到,则返回null,若匹配到:

(1)不带g,则只返回第一个完整匹配及其相关捕获组,与 exec 类似

'hello world'.match(/l([a-zA-Z])/) 
// ['ll', 'l', index: 2, input: 'hello world', groups: undefined]
// 用()包起来的就是捕获组,这里是l

'hello world'.match(/l(?<xx>[a-zA-Z])/)
// ['ll', 'l', index: 2, input: 'hello world', groups: {xx: 'l'}]
// (?<name>)是命名捕获组,这种会展示在groups里

(2)带g,则将返回与完整正则表达式匹配的所有结果,但不会返回捕获组。

'hello world'.match(/l([a-zA-Z])/g)
// ['ll', 'ld']
// 此处忽略了捕获组

2、replace

这个比较简单,主要需要注意特殊替换模式:其中最重要的是 $n(插入第 n(索引从 1 开始)个捕获组,其中 n 是小于 100 的正整数)

'1234567890'.replace(/(\d{4})(?=\d)/g, '$1 ')
// '1234 5678 90'
// 银行卡分段,匹配到4个数字后加一个空格

3、search

与indexOf类似,返回首次匹配到的下标,未匹配返回-1。indexOf效率较高,search可以传入正则表达式。

'hello'.search(/l/)
// 2

4、split

'a1b2c3'.split(/[a-zA-Z]/)
// ['', '1', '2', '3']

三、正则对象方法

1、exec

(1)不带g,与 match 类似

/l([a-zA-Z])/.exec('hello world')
['ll', 'l', index: 2, input: 'hello world', groups: undefined]

(2)带g,执行 exec 时会更新正则表达式的 lastIndex 属性,下次再次执行 exec 时会从 lastIndex 下标处开始(必需是同一个正则表达式)

const regex = /l[a-zA-Z]/g
regex.exec('hello world') // ['ll', index: 2, input: 'hello world', groups: undefined]
regex.lastIndex // 4
regex.exec('hello world') // ['ld', index: 9, input: 'hello world', groups: undefined]
regex.lastIndex // 11
regex.exec('hello world') // null
regex.lastIndex // 0

2、test

匹配到返回 true,没匹配到返回 false。

(1)不带g,类似 search,只是返回的是 boolean 值。

/abc/.test('123abc456')
// true

(2)带g,也是会更新 lastIndex 值。

const regex = /abc/g
regex.test('123abc456') // true
regex.test('123abc456') // false