命名反向引用:\k<名称>

命名反向引用指的是先前 命名捕获组 的子匹配,并匹配与该组相同的文本。对于 未命名的捕获组,你需要使用正常的 backreference 语法。

¥A named backreference refers to the submatch of a previous named capturing group and matches the same text as that group. For unnamed capturing groups, you need to use the normal backreference syntax.

语法

¥Syntax

regex
\k<name>

参数

¥Parameters

name

群组的名称。必须是有效的 identifier 并引用现有的命名捕获组。

描述

¥Description

命名反向引用与普通反向引用非常相似:它引用捕获组匹配的文本并匹配相同的文本。不同之处在于你通过名称而不是数字来引用捕获组。这使得正则表达式更具可读性并且更易于重构和维护。

¥Named backreferences are very similar to normal backreferences: it refers to the text matched by a capturing group and matches the same text. The difference is that you refer to the capturing group by name instead of by number. This makes the regular expression more readable and easier to refactor and maintain.

Unicode 不识别模式 中,如果正则表达式至少包含一个命名捕获组,则序列 \k 仅启动命名反向引用。否则,它是 身份逃避,与文字字符 k 相同。这是 已弃用的 Web 兼容性语法,你不应该依赖它。

¥In Unicode-unaware mode, the sequence \k only starts a named backreference if the regex contains at least one named capturing group. Otherwise, it is an identity escape and is the same as the literal character k. This is a deprecated syntax for web compatibility, and you should not rely on it.

js
/\k/.test("k"); // true

示例

¥Examples

配对报价

¥Pairing quotes

以下函数匹配字符串中的 title='xxx'title="xxx" 模式。为了确保引号匹配,我们使用反向引用来引用第一个引号。访问第二个捕获组 ([2]) 返回匹配引号字符之间的字符串:

¥The following function matches the title='xxx' and title="xxx" patterns in a string. To ensure the quotes match, we use a backreference to refer to the first quote. Accessing the second capturing group ([2]) returns the string between the matching quote characters:

js
function parseTitle(metastring) {
  return metastring.match(/title=(?<quote>["'])(.*?)\k<quote>/)[2];
}

parseTitle('title="foo"'); // 'foo'
parseTitle("title='foo' lang='en'"); // 'foo'
parseTitle('title="Named capturing groups\' advantages"'); // "Named capturing groups' advantages"

规范

Specification
ECMAScript Language Specification
# prod-AtomEscape

¥Specifications

浏览器兼容性

BCD tables only load in the browser

¥Browser compatibility

也可以看看