When should you use a regex, and when is it a bad idea?
Regular expressions are incredibly useful and famously easy to misuse. The old joke goes: you have a problem, you use regex, now you have two problems.
Good uses for regex
- Validating simple formats such as postal codes, IDs or date patterns
- Search and replace in editors and scripts
- Extracting fields from consistent log lines
- Quick filtering with tools like grep or ripgrep
Bad uses for regex
- Parsing HTML, XML or JSON; use a real parser instead
- Fully validating email addresses (the real spec is far more complex than most patterns allow)
- Anything with deeply nested or recursive structure
- Complex patterns nobody on the team can read
Pitfalls to watch for
- Catastrophic backtracking: some patterns with nested quantifiers can take exponential time on certain inputs, which has caused real outages and denial-of-service bugs
- Different regex flavors (PCRE, JavaScript, POSIX) behave differently
- Forgetting anchors, so a "validation" pattern matches a substring
Tips: use verbose or commented mode when your language supports it, test patterns against tricky inputs, and keep a tool like a regex tester handy.
What is the most useful regex you keep reusing? And what is the worst regex you have ever had to maintain?
Comments · 3
Use it for simple, well-defined patterns. If you can't explain it to a teammate in a sentence, it's probably time for a parser or clearer code.
Is there a point where named capture groups and comments make complex regexes acceptable? Or is it better to split into smaller steps?
Readable code is a form of UX for the next developer. A comment above the pattern is worth the extra line.