反向引用

摘要: 在本教程中,您将了解 JavaScript 正则表达式反向引用以及如何有效地应用它们。

JavaScript 正则表达式反向引用的介绍

反向引用允许您引用正则表达式中的捕获组。从技术上讲,反向引用就像正则表达式中的变量

以下是反向引用的语法

\NCode language: Python (python)

在此语法中,N 是一个整数,例如 1、2 和 3,表示相应的捕获组编号。

假设您有一个包含重复单词 JavaScript 的字符串,如下所示

const s = 'JavaScript JavaScript is awesome';Code language: Python (python)

您想删除重复的单词 (JavaScript),以便结果字符串为

'JavaScript is awesome'Code language: Python (python)

为此,您可以在正则表达式中使用反向引用。

首先,匹配一个单词

/\w+\s+/Code language: Python (python)

其次,创建一个捕获组,捕获该单词

/(\w+)\s+/Code language: Python (python)

第三,使用反向引用来引用第一个捕获组

/(\w+)\s+\1/Code language: Python (python)

在此模式中,\1 是一个反向引用,引用 (\w+) 捕获组。

最后,使用 String.replace() 方法将整个匹配项替换为第一个捕获组

const s = 'JavaScript JavaScript is cool';
const pattern = /(\w+)\s+\1/;

const result = s.replace(pattern, '$1');

console.log(result);
Code language: Python (python)

输出

JavaScript is coolCode language: Python (python)

JavaScript 正则表达式反向引用示例

以下示例展示了反向引用的实际应用。

1) 使用反向引用获取引号内的文本

要获取双引号内的文本,如下所示

"JavaScript Regex Backreferences"Code language: Python (python)

或单引号

'JavaScript Regex Backreferences'Code language: Python (python)

但不能混合使用单引号和双引号

'not match"Code language: Python (python)

为此,您可能会想出以下正则表达式

/[\'"](.*?)[\'"]/Code language: Python (python)

但是,此正则表达式还匹配以单引号 (‘) 开头并以双引号 (“) 结尾的文本,反之亦然。例如

const message = `"JavaScript's cool". They said`;
const pattern = /[\'"].*?[\'"]/;

const match = message.match(pattern);

console.log(match[0]);
Code language: Python (python)

它返回 "JavaScript' 而不是 "JavaScript's cool"

为了解决这个问题,您可以在正则表达式中使用反向引用

/([\'"]).*?\1/Code language: Python (python)

反向引用 \1 引用第一个捕获组。如果子组以单引号开头,则 \1 匹配单引号。如果子组以双引号开头,则 \1 匹配双引号。

例如

const message = `"JavaScript's cool". They said`;
const pattern = /([\'"]).*?\1/;

const match = message.match(pattern);

console.log(match[0]);
Code language: Python (python)

输出

"JavaScript's cool"Code language: Python (python)

2) 使用反向引用查找至少包含一个连续重复字符的单词

以下示例展示了如何使用反向引用来查找至少包含一个连续重复字符的单词,例如 apple (字母 p 重复)

const words = ['apple', 'orange', 'strawberry'];
const pattern = /\b\w*(\w)\1\w*\b/;

for (const word of words) {
  const result = word.match(pattern);
  if (result) {
    console.log(result[0], '->', result[1]);
  }
}Code language: Python (python)

输出

apple -> p
strawberry -> rCode language: Python (python)

总结

  • 使用反向引用来引用正则表达式中的捕获组。
本教程对您有帮助吗?