Regex Quick Reference

Regular expression syntax, flags, and common patterns with examples.

Character Classes

. Any character except newline
a.c matches "abc", "a1c"
\d Any digit (0-9)
\d{3} matches "123"
\D Any non-digit
\D+ matches "abc"
\w Word character (a-z, A-Z, 0-9, _)
\w+ matches "hello_1"
\W Non-word character
\W matches "@", " "
\s Whitespace (space, tab, newline)
a\sb matches "a b"
\S Non-whitespace character
\S+ matches "hello"
[abc] Any of a, b, or c
[aeiou] matches vowels
[^abc] Not a, b, or c
[^0-9] matches non-digits
[a-z] Character range (a to z)
[A-Za-z] matches letters

Quantifiers

* Zero or more times
ab*c matches "ac", "abc", "abbc"
+ One or more times
ab+c matches "abc", "abbc"
? Zero or one time (optional)
colou?r matches "color", "colour"
{n} Exactly n times
\d{4} matches "2024"
{n,} n or more times
\d{2,} matches "12", "123"
{n,m} Between n and m times
\d{2,4} matches "12", "1234"
*? Zero or more (lazy)
<.*?> matches first tag only
+? One or more (lazy)
".+?" matches first quoted string

Anchors

^ Start of string (or line with m flag)
^Hello matches "Hello world"
$ End of string (or line with m flag)
world$ matches "Hello world"
\b Word boundary
\bcat\b matches "cat" not "catch"
\B Non-word boundary
\Bcat matches "catch" not "cat"

Groups & Lookaround

(abc) Capturing group
(\d+)-(\d+) captures both numbers
(?:abc) Non-capturing group
(?:https?://) groups without capture
(?<name>abc) Named capturing group
(?<year>\d{4}) captures as "year"
\1 Backreference to group 1
(\w+)\s\1 matches "the the"
(?=abc) Positive lookahead
\d+(?=px) matches "10" in "10px"
(?!abc) Negative lookahead
\d+(?!px) matches "10" in "10em"
(?<=abc) Positive lookbehind
(?<=\$)\d+ matches "50" in "$50"
(?<!abc) Negative lookbehind
(?<!\$)\d+ matches "50" in "50"
a|b Alternation (a or b)
cat|dog matches "cat" or "dog"

Flags

g Global: find all matches
/a/g finds all "a" in string
i Case-insensitive matching
/hello/i matches "Hello", "HELLO"
m Multiline: ^ and $ match line boundaries
/^foo/m matches "foo" on any line
s Dotall: . matches newline too
/a.b/s matches "a\nb"
u Unicode: enable Unicode features
/\p{L}/u matches any letter

Common Patterns

Email Basic email validation
[\w.-]+@[\w.-]+\.[a-zA-Z]{2,}
URL HTTP/HTTPS URL
https?://[\w.-]+(?:/[\w./-]*)?
Phone (US) US phone number
\(?\d{3}\)?[-.\s]?\d{3}[-.\s]?\d{4}
IPv4 IP address v4
\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}
Date (ISO) YYYY-MM-DD format
\d{4}-(?:0[1-9]|1[0-2])-(?:0[1-9]|[12]\d|3[01])
Hex Color #RGB or #RRGGBB
#(?:[0-9a-fA-F]{3}){1,2}
HTML Tag Match HTML tags
<\/?[a-z][\s\S]*?>
Slug URL-friendly slug
^[a-z0-9]+(?:-[a-z0-9]+)*$