Regular Expressions
Build a pattern from a few readable pieces:
| Form | Meaning |
|---|---|
. | any character except a newline by default |
^ / $ | start / end anchors |
[abc] / [^abc] | allowed / excluded character set |
*, +, ?, {m,n} | repetition |
(…) / (?:…) | capturing / non-capturing group |
\b | word boundary in Python's re syntax |
Use raw strings for Python patterns so Python string escaping does not obscure regex escaping:
import re
text = "Order A-104, order B-208"
codes = re.findall(r"\b[A-Z]-\d{3}\b", text)
updated = re.sub(r"(?i)\border\b", "item", text)
is_code = re.fullmatch(r"[A-Z]-\d{3}", "A-104") is not None
Choose the operation deliberately: search() finds the first match anywhere, fullmatch() requires the entire input, findall() collects matches, and sub() replaces them. Test representative matches, non-matches, empty input, Unicode, and unusually long input before using a pattern on untrusted data.
Regex syntax differs between Python, JavaScript, editors, and command-line tools. Treat the Python re documentation as authoritative only for Python; use RegExr as an interactive scratchpad, not as the specification for every engine.