实现说明
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))