0%

javascript-regex-exec

javascript regex exec

exec是正则表达式的方法,用来返回匹配的字符串。

exec的返回值

exec的返回值是一个数组,数组的第一个元素是匹配的字符串,后面的元素是分组匹配的值。看一个列子:

1
2
3
4
const str = 'There are 3 dogs, 5 cats, 2 birds and 1 cow';
const regex = /(\d+) (cat|dog|bird|cow)/g;
const match = regex.exec(str);
console.log(match);

返回值如下:

1
2
3
4
5
6
7
8
[
'3 dog', // 匹配的整个字符串
'3', // 第一个分组匹配的值
'dog', // 第二个分组匹配的值
index: 10, // 匹配值对应的下标
input: 'There are 3 dogs, 5 cats, 2 birds and 1 cow', // 原始字符串
groups: undefined // 分组匹配的值
]

循环处理

exec通常配合while循环使用,一边遍历,一边处理结果。注意,如果使用while循环处理,需要正则表达式中添加/g标志。

1
2
3
4
5
6
7
8
9
const str = 'There are 3 dogs, 5 cats, 2 birds and 1 cow';
const regex = /(\d+) (cat|dog|bird|cow)/g; // 添加/g标志
let match;
const result = {};
while ((match = regex.exec(str)) !== null) {
result[match[2]] = match[1];
}

console.log(result);

输出结果:

1
2
3
4
5
6
{
dog: '3',
cat: '5',
bird: '2',
cow: '1'
}

/g标志

如果想要使用while循环来遍历所有匹配的字符串,需要使用/g标志。否则会导致while死循环。

match/matchAll vs exec

  1. match/matchAll - 一次性返回所有匹配的字符串。
  2. exec - 逐个返回匹配的字符串。

match/matchAll使用/g时,需要对结果进行遍历。
exec是一边遍历,一边处理结果。