0%

javascript-regex-groups

JavaScript Regex Groups

分组匹配是正则表达式中非常重要的一部分,它允许我们将多个字符组合在一起,并对它们进行操作。在JavaScript正则表达式中,我们可以使用括号 () 来创建一个分组。在这篇文章中,我们将学习如何使用分组匹配。

匿名分组

匿名分组的格式如下,其中 xxx 是要匹配的内容。匿名分组返回的匹配没有名字,只能通过数组下标的形式访问。

1
(xxx)

给定字符串Personal info: name: zdd, age: 18, gender: male,如果要从中提取出姓名,年龄和性别,则可以使用匿名分组来实现。

1
2
3
4
5
6
7
const str = `Personal info: name: zdd, age: 18, gender: male`;
const regex = /name: (\w+), age: (\d+), gender: (\w+)/;
const match = str.match(regex);
console.log(match); // 返回整个匹配 name: zdd, age: 18, gender: male
console.log(match[1]); // 第一个分组:zdd
console.log(match[2]); // 第二个分组:18
console.log(match[3]); // 第三个分组:male

在上面的例子中,正则表达式/name: (\w+), age: (\d+), gender: (\w+)/中有三个(),所以一共包含三个分组:

  • 第一个分组: \(w+) - 匹配zdd
  • 第二个分组:(\d+) - 匹配18
  • 第三个分组:(\w+) - 匹配male

使用匿名分组时,返回值是一个数组,数组第一个元素是整个匹配,我们要的分组匹配结果从数组第二个元素(下标1)开始,返回值如下:

1
2
3
4
5
6
7
8
9
[
'name: zdd, age: 18, gender: male',
'zdd', // 第一组
'18', // 第二组
'male', // 第三组
index: 0,
input: 'name: zdd, age: 18, gender: male',
groups: undefined
]

注意,使用匿名分组时,返回值中groups属性值为undefined,这个值只有使用命名匹配时才有值。

命名分组

命名分组的格式如下,其中 name 是分组的名称,xxx 是要匹配的内容。命名匹配返回的分组有名字,除了通过数组下标访问外,还可以通过对象属性的方式访问。

1
(?<name>xxx)

还是以上面的字符串为例,我们使用命名分组来提取姓名,年龄和性别。

1
2
3
4
5
6
7
const str = `Personal info: name: zdd, age: 18, gender: male`;
const regex = /name: (?<name>\w+), age: (?<age>\d+), gender: (?<gender>\w+)/;
const match = str.match(regex);
console.log(match.groups); // [Object: null prototype] { name: 'zdd', age: '18', gender: 'male' }
console.log(match.groups.name); // zdd
console.log(match.groups.age); // 18
console.log(match.groups.gender); // male

match返回值如下:与匿名匹配相比,命名匹配的返回值中groups属性不再是undefined,而是一个对象,对象的属性名就是分组的名称,属性值就是匹配的结果。

1
2
3
4
5
6
7
8
9
[
'name: zdd, age: 18, gender: male',
'zdd',
'18',
'male',
index: 0,
input: 'name: zdd, age: 18, gender: male',
groups: [Object: null prototype] { name: 'zdd', age: '18', gender: 'male' }
]

命名匹配的好处是,除了可以使用数组下标来访问分组匹配外,还可以使用groups字段来获取分组匹配。比如上面的match.groups.name就表示name分组对应的值。

再强调一次:groups字段只有在命名匹配时才有值,匿名匹配时用不到这个字段。