Backreferences in pattern N and k<name>
Backreferences in pattern: \N and \k<name>
The contents of capturing groups can be used not only in the replacement string or in the result, but also the pattern. (捕获组的内容不仅可以在替换字符串或结果中使用,还可以在模式中使用。)
In this chapter, we will explore backreference in the pattern such as \N and \k<name>.
Backreference by number: \N
Backreference by number: \N
In the pattern, a group can be referenced by using \N ( it is the group number). To make it more precise, let’s consider a case. (在模式中,可以通过使用\ N (它是组号)来引用组。 为了更准确,让我们考虑一个案例。)
Imagine, you want to find quoted strings. Both single-quoted and double-quoted variants should match. Now, let’s see how to find them. (想象一下,您想要查找带引号的字符串。单引号和双引号变体都应匹配。现在,让我们看看如何找到它们。)
Put both types of quotes into square brackets ’"[’"] is possible, but the strings with mixed quotes such as “…’ and ‘…” will be found. It may lead to incorrect matches as in the string “He is the one!”:
let str = `SHe said: "He's her brother!".`;
let regexp = /['"](.*?)['"]/g;
// The result is not what you want to see
console.log(str.match(regexp)); // "He'
So, the pattern found an opening quote, then the text is consumed until the other quote ‘. (因此,模式找到了一个开头引号,然后文本被消耗,直到另一个引号’。)
Let’s see the correct code:
let str = `She said: "He's her brother!".`;
let regexp = /(['"])(.*?)\1/g;
console.log(str.match(regexp)); // "He's her brother!"
Now, it works correctly. The engine of the regexp detects the initial quote ([’"])and remembers its content. (现在,它可以正常工作。正则表达式引擎检测初始引号([’"])并记住其内容。)
Further, \1 in the pattern considers “find the same text as in the initial group”. Like that, \2 means the contents of the second group, and so on. (此外,模式中的\ 1考虑“查找与初始组中相同的文本”。像这样,\ 2表示第二组的内容,以此类推。)
An important thing to note: if you apply ?: in the group, it can’t be referenced. Excluded from capturing (?:…) groups can not be remembered by the engine.
Backreference by name: \k<name>
Backreference by name: \k<name>
If there are many parentheses in a regexp, it is convenient to name them./p> (如果正则表达式中有许多括号,则可以方便地将其命名。/p >)
For referencing a named group, you can use \k<name>.
Let’s consider an example of a group with quotes. (让我们考虑一个带引号的小组示例。)
So, the name of the group will be ?<quote>, and the backreference will be \k<quote>,, like this:
let str = `SHe said: "He's her brother!".`;
let regexp = /(?<quote>['"])(.*?)\k<quote>/g;
console.log(str.match(regexp)); // "He's her brother!"