Regex Cheat Sheet
Every piece of regular expression syntax you’re likely to need, with an example you can open in the tester in one click.
Character classes
| Syntax | Meaning | Example | Try |
|---|---|---|---|
. | Any character except newline | /c.t/g | Try |
\d | Digit 0–9 | /\d+/g | Try |
\D | Not a digit | /\D+/g | Try |
\w | Word character [A-Za-z0-9_] | /\w+/g | Try |
\W | Not a word character | /\W/g | Try |
\s | Whitespace | /\s+/g | Try |
\S | Not whitespace | /\S+/g | Try |
[abc] | Any one of a, b or c | /gr[ae]y/g | Try |
[^abc] | Any character except a, b, c | /[^aeiou\s]/g | Try |
[a-z] | A range | /[A-F0-9]+/g | Try |
\p{L} | Any Unicode letter (u flag) JS | /\p{L}+/gu | Try |
Anchors & boundaries
Quantifiers
Groups & references
Lookaround
Flags
Common patterns
| Pattern for | Regex | Try |
|---|---|---|
| Email (practical) Good enough for form checks; the full RFC 5322 grammar is not a sensible regex | ^[^\s@]+@[^\s@]+\.[^\s@]{2,}$ | Try |
| URL (http/https) Links in text | https?:\/\/[^\s/$.?#].[^\s]* | Try |
| IPv4 address Four octets 0–255 | \b(?:(?:25[0-5]|2[0-4]\d|1?\d?\d)\.){3}(?:25[0-5]|2[0-4]\d|1?\d?\d)\b | Try |
| ISO date YYYY-MM-DD | \b\d{4}-(0[1-9]|1[0-2])-(0[1-9]|[12]\d|3[01])\b | Try |
| Hex colour #rgb or #rrggbb | #(?:[0-9a-fA-F]{3}){1,2}\b | Try |
| UUID 8-4-4-4-12 hex | \b[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\b | Try |
| Trailing whitespace Spaces at line ends | [ \t]+$ | Try |
| Duplicate words the the | \b(\w+)\s+\1\b | Try |
| Semantic version major.minor.patch | \bv?\d+\.\d+\.\d+(?:-[\w.]+)?\b | Try |
Questions
Does this apply to Python, PHP and Java too?
Nearly all of it. The table is written for JavaScript; rows marked “JS” behave differently or are missing in some other engines. Python uses (?P<name>…) for named groups, for example.
What is the difference between greedy and lazy?
Greedy quantifiers (*, +) take as much as they can and back off; lazy ones (*?, +?) take as little as possible. On <b>x</b>, <.+> matches the whole string while <.+?> matches just <b>.