A regular expression (regex) describes a pattern in text: “a number followed by letters”, “anything that looks like an email”. This cheat sheet covers the syntax used by JavaScript, Python, Java and most other languages, followed by ready patterns and the traps that make regexes slow or wrong. Test every pattern as you go with the Regex Tester.
Characters and classes
| Pattern | Matches |
|---|---|
. | Any character except a new line |
\d \D | A digit / a non-digit |
\w \W | A letter, digit or underscore / anything else |
\s \S | Whitespace / non-whitespace |
[abc] [^abc] | One of a, b, c / anything but those |
[a-z0-9] | A range |
\. \( | A literal dot or bracket (escape special characters with \) |
Quantifiers, anchors and groups
| Pattern | Meaning |
|---|---|
* + ? | 0 or more / 1 or more / 0 or 1 |
{3} {2,5} {2,} | Exactly 3 / between 2 and 5 / at least 2 |
*? +? | Lazy: as few as possible |
^ $ | Start / end of the text (or line, with the m flag) |
\b | A word boundary |
(abc) | A capturing group |
(?:abc) | A group that does not capture |
a|b | a or b |
(?=x) (?!x) | Followed by x / not followed by x |
Patterns you will actually use
| For | Pattern |
|---|---|
| Indian mobile number | ^[6-9]\d{9}$ |
| PIN code | ^[1-9]\d{5}$ |
| Date as dd-mm-yyyy | ^(0[1-9]|[12]\d|3[01])-(0[1-9]|1[0-2])-\d{4}$ |
| Simple email check | ^[^\s@]+@[^\s@]+\.[^\s@]+$ |
| URL starting http(s) | https?:\/\/[^\s]+ |
| Hex colour | ^#?([0-9a-fA-F]{3}|[0-9a-fA-F]{6})$ |
| Extra spaces | \s{2,} |
Flags
gfind all matches, not just the first.iignore case.mmake^and$match at each line.slet.match new lines too.
Mistakes to avoid
- Greedy surprises.
<.*>matches from the first<to the last>on the line. Use<.*?>or<[^>]*>. - Forgetting anchors. Without
^and$,\d{10}matches inside a 12-digit number. - Catastrophic backtracking. Nested repeats like
(a+)+$can freeze a program on certain input. Keep patterns simple and test with long, almost-matching text. - Parsing HTML or JSON with regex. Use a real parser; try the JSON Formatter to check JSON.
Frequently asked questions
Do all languages use the same regex syntax?
The basics are shared. Differences appear in lookbehind, named groups and Unicode support, so test in the language you use.
How do I replace with a group?
Refer to the group in the replacement, as $1 in JavaScript or \1 in Python, for example turning (\d{2})-(\d{2}) into $2/$1.