Programming43 entries

Regular Expressions

Regex syntax, character classes, quantifiers, groups, lookaheads, and common patterns

1Character Classes

.
Any character except newline
\d
Any digit [0-9]
\D
Any non-digit [^0-9]
\w
Any word character [a-zA-Z0-9_]
\W
Any non-word character
\s
Any whitespace (space, tab, newline)
\S
Any non-whitespace
[abc]
Match a, b, or c
[^abc]
Match anything except a, b, or c
[a-z]
Match any lowercase letter
[0-9]
Match any digit

2Quantifiers

*
Zero or more times
+
One or more times
?
Zero or one time (optional)
{3}
Exactly 3 times
{3,}
3 or more times
{3,5}
Between 3 and 5 times
*?
Zero or more (lazy/non-greedy)
+?
One or more (lazy/non-greedy)

3Anchors & Boundaries

^
Start of string (or line with m flag)
$
End of string (or line with m flag)
\b
Word boundary
\B
Non-word boundary

4Groups & References

(abc)
Capturing group
(?:abc)
Non-capturing group
(?<name>abc)
Named capturing group
\1
Back-reference to group 1
(a|b)
Match a or b (alternation)

5Lookahead & Lookbehind

(?=abc)
Positive lookahead (followed by abc)
(?!abc)
Negative lookahead (not followed by abc)
(?<=abc)
Positive lookbehind (preceded by abc)
(?<!abc)
Negative lookbehind (not preceded by abc)

6Flags

g
Global search (find all matches)
i
Case-insensitive search
m
Multi-line mode (^ and $ match line boundaries)
s
Dotall mode (. matches newlines)
u
Unicode mode

7Common Patterns

^[\w.-]+@[\w.-]+\.\w{2,}$
Email address (basic)
^https?://[\w.-]+(?:/\S*)?$
URL (basic)
^\d{1,3}(\.\d{1,3}){3}$
IPv4 address
^\d{4}-\d{2}-\d{2}$
Date (YYYY-MM-DD)
^#?([a-fA-F0-9]{6}|[a-fA-F0-9]{3})$
Hex color code
^\+?\d{10,15}$
Phone number (basic international)