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.

PythonData Integrity

Code

pythonsnippet
18 lines
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: True

How 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

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`.