← 中文资源

简体中文版本

re 反向引用匹配重复文本

反向引用要求分组捕获的文本原样重现:一段模式即可查重复词、要求引号成对闭合、校验键值相等,混合引号的错误配对会被自然排除。

阅读英文原文

运行结果

以下输出由构建管线在沙箱中真实运行该示例捕获。

repeated words: ['the', 'build']
repeat: (0, 7) the the
repeat: (34, 45) build build
quote pairs: [("'", 'hi'), ('"', 'bye')]
key equals value: True

实现说明

for match in re.finditer(r"\b(\w+)\s+\1\b", text, flags=re.IGNORECASE) 承担全部的逐项处理。 顶层就这几处状态:text、doubled、quoted、assign。

使用要点

  • 每一步打印都带着自己的标签:repeated words:、repeat:、quote pairs:。

常见问题

这个示例需要哪些包?

一个都不用。代码用到的符号都在标准库里解析。 文件用顶层绑定保存自己的状态:text、doubled、quoted。

核心语句

for match in re.finditer(r"\b(\w+)\s+\1\b", text, flags=re.IGNORECASE):
    print("repeat:", match.span(), match.group(0))

代码示例

import re

# A backreference \1 re-matches exactly what group 1 captured.
text = "the the deploy failed because the build build was stale"
doubled = re.findall(r"\b(\w+)\s+\1\b", text, flags=re.IGNORECASE)
print("repeated words:", doubled)

# finditer exposes span() so an editor could highlight each repeat.
for match in re.finditer(r"\b(\w+)\s+\1\b", text, flags=re.IGNORECASE):
    print("repeat:", match.span(), match.group(0))

# Matching quote pairs: the closing quote must be the same char group 1 saw.
quoted = re.findall(r"(['\"])(.*?)\1", "say 'hi' or \"bye\" but not 'mixed\"")
print("quote pairs:", quoted)

# Named groups stay readable; (?P=name) re-matches that named group.
assign = re.match(r"(?P<key>\w+)=(?P=key)", "token=token")
print("key equals value:", bool(assign))