
Learn to use regular expressions by following RegexTip. From @JohnDCook.
Joined November 2009
- Tweets5K
- Following19
- Followers73.9K
- Likes20
Pinned Tweet
Four tips for learning regular expressions
johndcook.com/blog/2008/01/1…
Finding words that can be spelled with chemical symbols using a regex.
The regex can either run in linear time or exponential time, depending on the regex engine.
johndcook.com/blog/2026/10/1…
Why can't grep find negative numbers? johndcook.com/blog/2019/12/0…
For ASCII-only case-insensitive matching, use an ASCII/locale mode if available because Unicode casefolding can be surprising.
\B is the negation of a word boundary. For example, /\Bcat\B/ matches 'scathing' (cat inside) but not 'cat' as a standalone word.
The characters * and ? have different meanings in regular expressions than they do in shells. Confusingly similar, but different.
Word boundary \b is a position between \w and \W, not a character. /\bcat\b/ matches 'cat' but not 'concatenate'.
What we call 'regular expressions' today includes more general patterns than the original definition from the 1950's.
Four tips for learning regular expressions johndcook.com/blog/2008/01/1…
Regex engines differ on what \s includes (e.g., non-breaking spaces). If exact whitespace matters, specify it explicitly.
.* will match as much as it can, but then backtrack if the next atom can also be matched. Backtracking on some engines is slow.
Greedy quantifiers (*, +, {m,n}) match as much as possible, then backtrack if needed. Lazy quantifiers (*?, +?, {m,n}?) match as little as possible.
Remember: \\ inside a string literal becomes \ in the regex. In Python, raw strings can be cleaner, e.g r'\d+' is easier ro read than '\\d+'.
Finding all English words with four or more consecutive vowels: johndcook.com/blog/2019/10/1…
To include a literal ^ in a character class, don't put it first: /[^^]/ matches any char except '^'.
? means a character or expression is optional, i.e. zero or one occurrences. Example: /ab?c/ matches 'ac' and 'abc' but not 'abbc'.
