re Backreferences Match Repeated Words
A backreference re-matches exactly what its group captured: repeated words fail a lint, quote pairs must close with the same character, keys equal values.
Code
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))Output
Captured from a sandboxed run of this snippet in the build pipeline.
repeated words: ['the', 'build']
repeat: (0, 7) the the
repeat: (34, 45) build build
quote pairs: [("'", 'hi'), ('"', 'bye')]
key equals value: TrueHow the snippet works
Iteration happens inside for match in re.finditer(r"\b(\w+)\s+\1\b", text, flags=re.IGNORECASE) — everything outside it runs once.
Module-level bindings hold the data — text, doubled, quoted, assign — with no function scope in between.
Applying it
Running the file prints labeled results such as repeated words:, repeat:, quote pairs: — each operation’s effect is visible in the output.
Statements that matter
for match in re.finditer(r"\b(\w+)\s+\1\b", text, flags=re.IGNORECASE):
print("repeat:", match.span(), match.group(0))
Interactive Tools for This Topic
Regex Backreference ExplainerScan a regular expression to list its capturing groups, named groups, non-capturing groups, and backreferences, with warnings for dangling references.Regular Expression TesterTest regular expressions against sample text with live match highlighting, capture group extraction, and flags support for global, case-insensitive, and multiline modes.Fuzzy Match TesterTest subsequence fuzzy matching: check whether pattern characters appear in order inside a text, with positions and highlighting.Glob Pattern TesterCompile glob patterns with *, **, ?, character classes, and braces into regex and test them against a list of candidate file paths.
FAQ
- Which packages does this snippet need?
- None. Every symbol the code uses resolves inside the standard library. Its state lives in module-level bindings: `text`, `doubled`, `quoted`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.