Regular Expressions Cheatsheet
Basic Patterns
.- Any character except newline\w- Word character [A-Za-z0-9_]\W- Non-word character\d- Digit [0-9]\D- Non-digit\s- Whitespace (space, tab, newline)\S- Non-whitespace\b- Word boundary\B- Non-word boundary
Anchors
^- Start of string/line$- End of string/line\A- Start of string only\Z- End of string only
Character Classes
[abc]- Any character a, b, or c[^abc]- Any character except a, b, c[a-z]- Any lowercase letter[A-Z]- Any uppercase letter[0-9]- Any digit[a-zA-Z]- Any letter[a-zA-Z0-9]- Any letter or digit
Quantifiers
*- 0 or more+- 1 or more?- 0 or 1{n}- Exactly n times{n,}- n or more times{n,m}- Between n and m times*?- Lazy match (0 or more)+?- Lazy match (1 or more)
Groups and References
(...)- Capturing group(?:...)- Non-capturing group(?<name>...)- Named capturing group\1,\2- Backreference to group\k<name>- Backreference to named group
Alternation
|- OR operator(?:|)- OR in non-capturing group
Lookarounds
(?=...)- Positive lookahead(?!...)- Negative lookahead(?<=...)- Positive lookbehind(?<!...)- Negative lookbehind
Common Patterns
# Email
^[\w\.-]+@[\w\.-]+\.\w+$
# URL
^(https?:\/\/)?([\da-z\.-]+)\.([a-z\.]{2,6})([\/\w \.-]*)*\/?$
# Phone Number (US)
^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$
# Date (YYYY-MM-DD)
^\d{4}-(0[1-9]|1[0-2])-(0[1-9]|[12]\d|3[01])$
# Strong Password
^(?=.*[A-Za-z])(?=.*\d)(?=.*[@$!%*#?&])[A-Za-z\d@$!%*#?&]{8,}$
Modifiers
i- Case-insensitiveg- Global searchm- Multilines- Single line (dot matches newline)u- Unicodey- Sticky search
Special Characters Escaping
\.- Literal dot\*- Literal asterisk\+- Literal plus\?- Literal question mark\[- Literal square bracket\(- Literal parenthesis\\- Literal backslash