# 正则 match & exec 区别

# 使用

  • string.match(reg)
  • RegExp.exec(str)

# match

  1. 当正则为全局表达式 //g 时,返回所有的匹配结果的组成的数组
'这是123一个456字符串'.match(/(\d)(\d)(\d)/g)
// ["123", "456"]
1
2
  1. 当正则不是全局表达式 // 时,返回一个数组,数组第一个元素为第一个与reg匹配的字符串,余下参数为与字符串中的圆括号匹配的字符串,还有index表示当前发生匹配的位置,input表示当前正在检索的字符串
'这是123一个456字符串'.match(/(\d)(\d)(\d)/)

// 数组:
// 0: "123"
// 1: "1"
// 2: "2"
// 3: "3"
// groups: undefined
// index: 2
// input: "这是123一个456字符串"
// length: 4
1
2
3
4
5
6
7
8
9
10
11

# exec

无论正则是否为全局匹配,都返回一个数组,该数组的结果的元素含义与 match 方法的非全局匹配结果的元素含义一致。

  1. 当正则为全局表达式 //g 时,会返回包含第一个匹配结果的数组, 然后把 lastIndex 属性设置为当前匹配结果的结束处的位置。当再一次调用 exec() 时, 会继续从 lastIndex 位置开始查找。直到查找结果为 null,则把 lastIndex 设为 0,下一轮重头查找。
const reg = /(\d)(\d)(\d)/g

reg.exec('这是123一个456字符串')
//  ["123", "1", "2", "3", index: 2, input: "这是123一个456字符串", groups: undefined]

console.log(reg.lastIndex) // 5

reg.exec('这是123一个456字符串')
// ["456", "4", "5", "6", index: 7, input: "这是123一个456字符串", groups: undefined]

console.log(reg.lastIndex) // 10

reg.exec('这是123一个456字符串')
// null

console.log(reg.lastIndex) // 0

// 重头开始匹配
reg.exec('这是123一个456字符串')
//  ["123", "1", "2", "3", index: 2, input: "这是123一个456字符串", groups: undefined]
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
  1. 当正则不是全局表达式 // 时,每次都会返回包含第一个匹配结果的数组,lastIndex 一直为 0
const reg = /(\d)(\d)(\d)/

reg.exec('这是123一个456字符串')
//  ["123", "1", "2", "3", index: 2, input: "这是123一个456字符串", groups: undefined]

console.log(reg.lastIndex) // 0
1
2
3
4
5
6

# test

RegExp.test(str) 方法表现的和 exec 一样,也会维护 lastIndex属性。

const reg = /(\d)(\d)(\d)/g

reg.test('这是123一个456字符串') // true
reg.test('这是123一个456字符串') // true
reg.test('这是123一个456字符串') // false
1
2
3
4
5
最后更新时间: 9/4/2021, 2:36:04 PM