Tips that save you regex pain
- Always anchor when you mean to validate. A pattern without
^and$matches if it's found anywhere in the string — not what you usually want for validation. - Use raw strings. In Python:
r"\\d+". In JavaScript: prefer regex literals/\\d+/overnew RegExp("\\\\d+"), since string escaping doubles the backslashes. - Be careful with greedy quantifiers.
.*will match as much as possible, then backtrack. Use.*?(lazy) or[^"]*(specific) when extracting fields. - Watch for catastrophic backtracking. Nested quantifiers like
(a+)+can cause exponential runtime on certain inputs. This is called ReDoS — see our explainer which warns about it. - Comment complex regexes. Most flavors support an extended/verbose mode (
xflag) that lets you spread regex across lines with comments.