JavaScript Regex Groups
分组匹配是正则表达式中非常重要的一部分,它允许我们将多个字符组合在一起,并对它们进行操作。在 JavaScript 中,我们可以使用括号 ()
来创建一个分组。在这篇文章中,我们将学习如何使用分组匹配。
匿名分组
匿名分组的格式如下,其中 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); console.log(match[1]); console.log(match[2]); console.log(match[3]);
|
使用匿名分组时,返回值是一个数组,数组第一个元素是整个匹配,我们要的分组结果从数组第二个元素开始(下标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 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); console.log(match.groups.name); console.log(match.groups.age); console.log(match.groups.gender);
|
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' } ]
|