命名捕获组:(?<名称>...)

命名捕获组是一种特殊类型的 捕获组,它允许为该组命名。稍后可以通过该名称而不是通过其在模式中的索引来识别组的匹配结果。

¥A named capturing group is a particular kind of capturing group that allows to give a name to the group. The group's matching result can later be identified by this name instead of by its index in the pattern.

语法

¥Syntax

regex
(?<name>pattern)

参数

¥Parameters

pattern

由你可以在正则表达式文字中使用的任何内容组成的模式,包括 disjunction

name

群组的名称。必须是有效的 identifier

描述

¥Description

命名捕获组可以像捕获组一样使用 - 它们在结果数组中也有匹配索引,并且可以通过 \1\2 等引用它们。唯一的区别是它们可以通过名称另外引用。捕获组的匹配信息可以通过以下方式访问:

¥Named capturing groups can be used just like capturing groups — they also have their match index in the result array, and they can be referenced through \1, \2, etc. The only difference is that they can be additionally referenced by their name. The information of the capturing group's match can be accessed through:

同一模式中的所有名称必须是唯一的。多个具有相同名称的命名捕获组会导致语法错误。

¥All names must be unique within the same pattern. Multiple named capturing groups with the same name result in a syntax error.

js
/(?<name>)(?<name>)/; // SyntaxError: Invalid regular expression: Duplicate capture group name

如果重复的命名捕获组不在同一个 析取替代 中,则可以放宽此限制,因此对于任何字符串输入,实际上只能匹配一个命名捕获组。这是一个较新的功能,因此在使用之前请检查 浏览器兼容性

¥This restriction is relaxed if the duplicate named capturing groups are not in the same disjunction alternative, so for any string input, only one named capturing group can actually be matched. This is a much newer feature, so check browser compatibility before using it.

js
/(?<year>\d{4})-\d{2}|\d{2}-(?<year>\d{4})/;
// Works; "year" can either come before or after the hyphen

命名的捕获组将全部出现在结果中。如果命名捕获组不匹配(例如,它属于 disjunction 中不匹配的替代项),则 groups 对象上的相应属性的值为 undefined

¥Named capturing groups will all be present in the result. If a named capturing group is not matched (for example, it belongs to an unmatched alternative in a disjunction), the corresponding property on the groups object has value undefined.

js
/(?<ab>ab)|(?<cd>cd)/.exec("cd").groups; // [Object: null prototype] { ab: undefined, cd: 'cd' }

你可以使用 d 标志获取输入字符串中每个命名捕获组的开始和结束索引。除了通过 exec() 返回的数组的 indices 属性来访问它们之外,你还可以通过 indices.groups 上的名称来访问它们。

¥You can get the start and end indices of each named capturing group in the input string by using the d flag. In addition to accessing them on the indices property on the array returned by exec(), you can also access them by their names on indices.groups.

与未命名捕获组相比,命名捕获组具有以下优点:

¥Compared to unnamed capturing groups, named capturing groups have the following advantages:

  • 它们允许你为每个子匹配结果提供描述性名称。
  • 它们允许你访问子匹配结果,而不必记住它们在模式中出现的顺序。
  • 重构代码时,你可以更改捕获组的顺序,而不必担心破坏其他引用。

示例

¥Examples

使用命名捕获组

¥Using named capturing groups

以下示例从 Git 日志条目中解析时间戳和作者名称(输出为 git log --format=%ct,%an -- filename):

¥The following example parses a timestamp and an author name from a Git log entry (output with git log --format=%ct,%an -- filename):

js
function parseLog(entry) {
  const { author, timestamp } = /^(?<timestamp>\d+),(?<author>.+)$/.exec(
    entry,
  ).groups;
  return `${author} committed on ${new Date(
    parseInt(timestamp) * 1000,
  ).toLocaleString()}`;
}

parseLog("1560979912,Caroline"); // "Caroline committed on 6/19/2019, 5:31:52 PM"

规范

Specification
ECMAScript Language Specification
# prod-Atom

¥Specifications

浏览器兼容性

BCD tables only load in the browser

¥Browser compatibility

也可以看看