Basic Syntax

Literal Characters

Match exact characters:

cat # Matches "cat"
hello # Matches "hello"

Character Classes

PatternMatches
[abc]Any single character: a, b, or c
[^abc]Any character EXCEPT a, b, or c
[a-z]Any lowercase letter
[A-Z]Any uppercase letter
[0-9]Any digit
[a-zA-Z]Any letter (upper or lower)
[a-zA-Z0-9]Any letter or digit

Predefined Character Classes

PatternEquivalentMatches
\d[0-9]Any digit
\D[^0-9]Any non-digit
\w[a-zA-Z0-9_]Any word character (letter, digit, underscore)
\W[^a-zA-Z0-9_]Any non-word character
\s[ \t\n\r\f\v]Any whitespace (space, tab, newline)
\S[^ \t\n\r\f\v]Any non-whitespace
.-Any character except newline

Quantifiers

PatternMatches
*0 or more times
+1 or more times
?0 or 1 time (optional)
{n}Exactly n times
{n,}n or more times
{n,m}Between n and m times

Examples:

\d+ # One or more digits: "123", "5"
\d{3} # Exactly 3 digits: "123", "456"
\d{2,4} # 2 to 4 digits: "12", "123", "1234"
colou?r # "color" or "colour"
https? # "http" or "https"

Anchors

PatternMatches
^Start of string/line
$End of string/line
\bWord boundary
\BNot a word boundary

Examples:

^hello # "hello" at start: "hello world" ✓, "say hello" ✗
world$ # "world" at end: "hello world" ✓, "world peace" ✗
\bcat\b # "cat" as whole word: "cat" ✓, "category" ✗

Grouping and Alternation

PatternMeaning
(...)Capturing group
(?:...)Non-capturing group
``

Examples:

(cat|dog) # Matches "cat" OR "dog"
gr(a|e)y # Matches "gray" OR "grey"
(\d{3})-\d{4} # Matches "123-4567" (captures "123")