hello # Matches "hello" literally
. # Matches any single character except newline
\ # Escape character
\n # Newline
\t # Tab
\r # Carriage return
Basic regex characters
Character Classes
[abc] # Matches a, b, or c
[^abc] # Matches any character except a, b, or c
[a-z] # Matches any lowercase letter
[A-Z] # Matches any uppercase letter
[0-9] # Matches any digit
[a-zA-Z0-9] # Matches any alphanumeric
Character set matching
Predefined Classes
\d # Digit: [0-9]
\D # Non-digit: [^0-9]
\w # Word character: [a-zA-Z0-9_]
\W # Non-word character
\s # Whitespace: [ \t\n\r\f]
\S # Non-whitespace
. # Any character except newline
Common character shortcuts
Quantifiers
Basic Quantifiers
* # Zero or more times
+ # One or more times
? # Zero or one time
{n} # Exactly n times
{n,} # n or more times
{n,m} # Between n and m times
^ # Start of line/string
$ # End of line/string
\A # Start of string (ignores multiline)
\Z # End of string (ignores multiline)
\b # Word boundary
\B # Non-word boundary
Position matching
Examples:
^hello # "hello" at start of line
world$ # "world" at end of line
\bword\b # "word" as whole word
Examples:
\d+(?=px) # Digits followed by "px"
\w+(?!@) # Word not followed by "@"
(?<=\$)\d+ # Digits preceded by "$"
Groups and Capturing
Grouping
(pattern) # Capturing group
(?:pattern) # Non-capturing group
(?pattern) # Named group
\1, \2, \3 # Backreferences to groups
\k # Backreference to named group
Grouping and referencing
Examples:
(abc)+ # "abc", "abcabc"
(?:abc)+ # Same match, no capture
(?\w+)\s+\k # Repeated word
Alternation
| # OR operator
(cat|dog) # Matches "cat" or "dog"
gr(a|e)y # Matches "gray" or "grey"
Matching alternatives
Examples:
(com|org|net) # "com" or "org" or "net"
(Mr|Mrs|Ms)\. # Titles with period
Common Patterns
Email Validation
[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}
# More comprehensive:
^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$
# MM/DD/YYYY:
^(0[1-9]|1[0-2])/(0[1-9]|[12][0-9]|3[01])/\d{4}$
# YYYY-MM-DD:
^\d{4}-(0[1-9]|1[0-2])-(0[1-9]|[12][0-9]|3[01])$
# Time (HH:MM):
^([01]?[0-9]|2[0-3]):[0-5][0-9]$
Date and time patterns
Matches:
12/25/2023
2023-12-25
14:30
Passwords
# At least 8 chars, 1 uppercase, 1 lowercase, 1 digit:
^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)[a-zA-Z\d@$!%*?&]{8,}$
# At least 8 chars with special chars:
^(?=.*[A-Za-z])(?=.*\d)(?=.*[@$!%*#?&])[A-Za-z\d@$!%*#?&]{8,}$
g # Global (find all matches)
i # Case insensitive
m # Multiline (^ and $ match line breaks)
s # Dotall (dot matches newlines)
u # Unicode
y # Sticky (matches at lastIndex)
Regex matching modifiers
Examples:
/hello/gi # Global, case insensitive
/multiline/m # Multiline mode