Reason about Atomic Groups and Backtracking
Core idea
A backtracking engine may revisit earlier choices when later parts fail. Python 3.11+ supports atomic groups (?>...) and possessive quantifiers such as *+; they prevent reconsidering choices inside the committed region. This can change matching results, not just speed.
import reprint(bool(re.fullmatch(r"a*a", "aaa")))print(bool(re.fullmatch(r"a*+a", "aaa")))The ordinary star gives one a back to the final atom; the possessive star does not.
Commit to an alternative
import reprint(bool(re.fullmatch(r"(?:ab|a)b", "ab")))print(bool(re.fullmatch(r"(?>ab|a)b", "ab")))The atomic group commits to ab and cannot retry a after the final b fails.
Common mistake
Nested ambiguous repetitions can make failure very expensive. Prefer simple unambiguous patterns, bound untrusted input length, avoid accepting arbitrary user patterns, and isolate matching with a real resource limit when needed. Python re has no per-match timeout argument. Atomic groups alone do not guarantee safe runtime.
Practice
On short synthetic text only, compare aa and a+a for "a" and "aaa"; explain the difference. Do not benchmark unbounded ambiguous patterns.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Backtracking and atomicity
Check your understanding of atomic groups and backtracking.
What is printed?
import reprint(bool(re.fullmatch(r"b+b","bb")), bool(re.fullmatch(r"b++b","bb")))What is printed?
import reprint(bool(re.fullmatch(r"(?:xy|x)y","xy")), bool(re.fullmatch(r"(?>xy|x)y","xy")))What is a useful defense for matching untrusted text?
Which Python version introduced atomic groups in re?