Programming & Development Cheat Sheet

Regex Cheat Sheet: Syntax, Examples & Common Patterns

A practical regular expression reference covering character classes, anchors, quantifiers, groups, lookarounds, flags, common patterns, replacements, and important differences between regex engines.

  • Copyable regex syntax
  • Practical matching examples
  • Interactive regex tester
  • Flavor compatibility notes
16 structured sections Beginner to advanced JavaScript, Python, Java, PCRE, and RE2

Essential regex syntax

Regex Quick Reference

Start with the most frequently used regular expression symbols. These constructs work in most modern regex engines unless noted otherwise later in this guide.

Common regular expression syntax, meanings, and examples
Syntax Meaning Example Copy
. Matches almost any single character except a line break by default. c.t matches cat and cut.
\d Matches a digit. Unicode behavior varies by regex engine. \d{4} matches 2026.
\w Matches a word character. The exact character set depends on the engine and mode. \w+ matches user_42.
\s Matches whitespace such as a space, tab, or line break. \s+ matches one or more whitespace characters.
[abc] Matches one character listed inside the brackets. gr[ae]y matches gray and grey.
[^abc] Matches one character not listed inside the brackets. [^0-9] matches a non-digit character.
^ Matches the start of the input, or the start of a line in multiline mode. ^Error matches text that begins with Error.
$ Matches the end of the input, or the end of a line in multiline mode. \.pdf$ matches text ending in .pdf.
* Matches the preceding token zero or more times. ab* matches a, ab, and abb.
+ Matches the preceding token one or more times. ab+ matches ab and abb, but not a.
? Matches the preceding token zero or one time. colou?r matches color and colour.
{n,m} Matches the preceding token from n through m times. \d{2,4} matches two to four digits.
(abc) Groups tokens and captures the matched text. (ha)+ matches ha, haha, and longer repetitions.
a|b Matches either the expression on the left or the expression on the right. cat|dog matches cat or dog.

Match special characters literally

Literal Characters and Escaping

Most letters and numbers match themselves. Add a backslash before a regex metacharacter when you need to match that character literally.

Regex metacharacters and escaped literal examples
Match Regex Example result Copy
Literal period \. Matches the period in file.pdf.
Literal plus sign \+ Matches the plus sign in C++.
Literal asterisk \* Matches the asterisk in 5*.
Literal question mark \? Matches the question mark in Ready?.
Literal parentheses \(text\) Matches (text), including both parentheses.
Literal square brackets \[item\] Matches [item], including both brackets.
Literal curly braces \{2\} Matches the literal text {2}.
Literal pipe \| Matches the separator in red|blue.
Literal backslash \\ Matches one backslash in the input text.
Literal dollar sign \$ Matches the dollar sign in $25.

JavaScript regex literal

Forward slashes delimit a regex literal, so a literal slash must be escaped inside it.

/https:\/\/example\.com/

Python raw string

Prefixing the pattern with r prevents Python string escaping from consuming regex backslashes.

r"\d+\.\d+"

Java string literal

Java string literals require each regex backslash to be escaped with another backslash.

"\\d+\\.\\d+"

Match categories of characters

Regex Character Classes

Character classes match one character from a defined set. Use brackets for custom sets and shorthand classes for common categories such as digits, whitespace, and word characters.

Regex character classes with meanings and examples
Class Meaning Example Copy
[abc] Matches one listed character. [abc] matches a, b, or c.
[^abc] Matches one character not included in the set. [^aeiou] matches a character other than a lowercase vowel.
[a-z] Matches one lowercase ASCII letter from a through z. [a-z]+ matches regex.
[A-Za-z] Matches one uppercase or lowercase ASCII letter. [A-Za-z]+ matches Regex.
[0-9] Matches one ASCII digit from zero through nine. [0-9]{4} matches 2026.
\d Matches a digit according to the engine’s character rules. \d+ matches a sequence of digits.
\D Matches a character that is not a digit. \D+ matches the letters in Room42.
\w Matches a word character; ASCII and Unicode behavior varies by engine. \w+ commonly matches user_42.
\W Matches a character that is not a word character. \W+ matches the space and hyphen in one - two.
\s Matches whitespace, typically including spaces, tabs, and line breaks. \s+ matches consecutive whitespace.
\S Matches a character that is not whitespace. \S+ matches the next non-whitespace token.
. Matches almost any character, usually excluding line breaks unless dot-all mode is enabled. a.c matches abc and a-c.
[\s\S] Common JavaScript-compatible technique for matching any character, including line breaks. [\s\S]* can span multiple lines without the dot-all flag.
\p{L} Matches a Unicode letter in engines that support Unicode property escapes. \p{L}+ can match letters from multiple writing systems.

Match positions instead of characters

Regex Anchors and Boundaries

Anchors and boundaries match positions in the input. They let you require a match at the beginning or end of text, at line boundaries, or between word and non-word characters.

Regex anchors and boundaries with examples
Syntax Meaning Example Copy
^ Matches the start of the input, or the start of a line in multiline mode. ^Error matches Error only at an allowed starting position.
$ Matches the end of the input, or the end of a line in multiline mode. done$ matches done at an allowed ending position.
\b Matches a word boundary without consuming a character. \bcat\b matches cat but not catalog.
\B Matches a position that is not a word boundary. \Bcat can match cat inside copycat.
^pattern$ Requires the entire allowed input or line to match the pattern. ^[0-9]{5}$ matches exactly five ASCII digits.
\A Matches the absolute start of the string in Python, Java, PCRE, and several other engines. \AStart is unaffected by multiline mode.
\z Matches the absolute end in Python 3.14+, Java, PCRE2, and RE2, but is not supported by JavaScript. end\z requires end at the absolute end.

Validate a complete value

Add start and end anchors when the entire value must follow the format, rather than merely contain a matching substring.

^[A-Z]{2}-[0-9]{4}$

Match complete words

Word boundaries help avoid partial matches, but their behavior still depends on how the engine defines a word character.

\b(?:cat|dog)\b

Control repetition

Regex Quantifiers

Quantifiers specify how many times the preceding character, class, or group may repeat. Most quantifiers are greedy by default and can be made lazy by adding a question mark.

Regex quantifiers with meanings and examples
Quantifier Meaning Example Copy
* Matches the preceding token zero or more times. go* matches g, go, and goo.
+ Matches the preceding token one or more times. go+ matches go and goo, but not g.
? Matches the preceding token zero or one time. colou?r matches color and colour.
{n} Matches the preceding token exactly n times. [0-9]{4} matches exactly four ASCII digits.
{n,} Matches the preceding token at least n times. a{2,} matches aa, aaa, and longer runs.
{n,m} Matches from n through m repetitions. [A-Z]{2,5} matches two to five uppercase ASCII letters.
*? Lazy form of *; expands only as far as needed for the match. <.*?> finds the shortest available angle-bracketed span.
+? Lazy form of +; requires at least one repetition. ".+?" finds the shortest available quoted span containing text.
{n,m}? Lazy bounded quantifier; prefers the smallest permitted count. \d{2,4}? initially prefers two digits when a match is possible.
*+ Possessive form of *; consumes without backtracking in supporting engines. Supported by Python 3.11+, Java, and PCRE2, but not by JavaScript or RE2.

Greedy match

A greedy quantifier consumes as much input as possible while still allowing the complete expression to match.

<.*>

Lazy match

A lazy quantifier begins with the shortest possible match and expands only when the rest of the expression requires it.

<.*?>

Organize, capture, and reuse matches

Regex Groups and Alternation

Groups combine multiple tokens into one unit. Capturing groups store matched text, non-capturing groups organize patterns without creating a capture, and alternation selects between alternatives.

Regex groups, backreferences, and alternation examples
Syntax Meaning Example Copy
(abc) Captures the text matched by the expression inside the parentheses. (ha)+ treats ha as one repeating unit.
(?:abc) Groups tokens without creating a numbered capture. (?:cat|dog)s? matches singular or plural forms.
a|b Matches the expression on the left or the expression on the right. red|blue matches either color name.
(cat|dog) Limits alternation to the expressions inside the group. ^(cat|dog)$ accepts only cat or dog.
\1 Backreferences the text captured by the first numbered group in supporting engines. \b(\w+)\s+\1\b finds an immediately repeated word.
(?<name>abc) Creates a named capturing group in JavaScript, Java, and PCRE2. (?<year>[0-9]{4}) captures four digits as year.
(?P<name>abc) Creates a Python-style named capturing group; also accepted by PCRE2 and RE2. (?P<year>[0-9]{4}) captures four digits as year.
\k<name> References a named group inside JavaScript, Java, and PCRE2 patterns. (?<word>\w+)\s+\k<word> finds a repeated word.
(?P=name) References a named group inside a Python regex pattern. (?P<word>\w+)\s+(?P=word) finds a repeated word.

Capture date components

Groups can separate a structured value into parts that your code can read individually.

^([0-9]{4})-([0-9]{2})-([0-9]{2})$

Repeat alternatives

A non-capturing group is useful when alternatives must repeat but their matched text does not need to be stored separately.

^(?:yes|no)(?:,(?:yes|no))*$

Test surrounding text

Regex Lookaheads and Lookbehinds

Lookaround assertions require or reject surrounding text without including that text in the matched result. Support and lookbehind restrictions vary between regex engines.

Positive and negative regex lookaround syntax with examples
Syntax Meaning Example Copy
(?=abc) Positive lookahead: requires the following text to match. \d+(?=px) matches digits followed by px.
(?!abc) Negative lookahead: requires the following text not to match. foo(?!bar) matches foo when it is not followed by bar.
(?<=abc) Positive lookbehind: requires the preceding text to match. (?<=\$)[0-9]+ matches digits preceded by a dollar sign.
(?<!abc) Negative lookbehind: requires the preceding text not to match. (?<!\$)[0-9]+ starts matching digits not immediately preceded by a dollar sign.
^(?=.*[A-Z]) Requires at least one uppercase ASCII letter somewhere ahead. Useful as one condition in a larger validation pattern.
^(?!.*\s) Rejects a value containing whitespace. Useful as one condition in a username or identifier pattern.

Match a number before a unit

The lookahead checks for px, but the unit is not included in the returned match.

\b[0-9]+(?=px\b)

Match text after a prefix

The lookbehind requires ID: before the digits without including that prefix in the returned match.

(?<=ID:)[0-9]+

Change matching behavior

Regex Flags and Modes

Flags control behavior such as case sensitivity, multiline anchors, dot matching, Unicode handling, and repeated matching. Available flags and the way they are enabled depend on the regex engine.

Common regex flags and modes with compatibility notes
Flag or mode Behavior Example or compatibility Copy
i Enables case-insensitive matching. /regex/i matches Regex in JavaScript.
m Allows ^ and $ to match at line boundaries. Commonly called multiline mode.
s Allows the dot wildcard to match line terminators. Commonly called dot-all or single-line mode.
g Continues finding matches after the first result in JavaScript. /cat/g can find every occurrence with the relevant JavaScript API.
u Enables Unicode-aware parsing for a JavaScript regex. Required for JavaScript Unicode property escapes such as \p{L}.
y Makes a JavaScript regex sticky at its current lastIndex position. Useful for tokenizers and sequential parsing.
x Allows formatting whitespace and comments in supporting engines. Available as verbose or comments mode in Python, Java, and PCRE, but not as a JavaScript flag.
(?i) Enables case-insensitive matching from inside the pattern in supporting engines. Supported by Python, Java, PCRE, and RE2; not supported by JavaScript.
(?m) Enables multiline matching from inside the pattern in supporting engines. Supported by Python, Java, PCRE, and RE2; not supported by JavaScript.
(?s) Enables dot-all matching from inside the pattern in supporting engines. Supported by Python, Java, PCRE, and RE2; not supported by JavaScript.

JavaScript flags

JavaScript places flags after the closing slash of a regex literal.

/^error:.*$/gim

Python flags

Python commonly passes flags to a function from the re module.

re.compile(r"^error:.*$", re.I | re.M)

Java flags

Java can pass flag constants when compiling a Pattern.

Pattern.compile("^error:.*$", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE)

Copyable practical examples

Common Regex Patterns

Use these patterns as readable starting points for common formatting tasks. Adjust length limits, allowed characters, Unicode behavior, and business rules before using them in production.

Common copyable regular expression patterns
Use case Pattern Important limitation Copy
Signed integer ^-?[0-9]+$ ASCII digits only; does not enforce a numeric range.
Decimal number ^-?(?:[0-9]+(?:\.[0-9]+)?|\.[0-9]+)$ Uses a period as the decimal separator and excludes exponent notation.
ISO-style date ^[0-9]{4}-(?:0[1-9]|1[0-2])-(?:0[1-9]|[12][0-9]|3[01])$ Checks the shape and basic ranges, not whether the calendar date exists.
24-hour time ^(?:[01][0-9]|2[0-3]):[0-5][0-9]$ Matches HH:MM without seconds or a time zone.
ASCII username ^[A-Za-z][A-Za-z0-9_]{2,19}$ Requires 3–20 characters and a leading ASCII letter.
Lowercase URL slug ^[a-z0-9]+(?:-[a-z0-9]+)*$ Allows lowercase ASCII letters, digits, and single internal hyphens.
Hex color ^#(?:[0-9A-Fa-f]{3}|[0-9A-Fa-f]{6})$ Accepts three- or six-digit hexadecimal colors, not alpha values.
Simple email shape ^[^\s@]+@[^\s@]+\.[^\s@]+$ Useful for a basic UI check; it is not full email-address validation.
HTTP or HTTPS URL shape ^https?:\/\/[^\s]+$ Checks a basic URL shape; use a platform URL parser for validation.
IPv4-like shape ^(?:[0-9]{1,3}\.){3}[0-9]{1,3}$ Does not restrict each number to the valid range of 0–255.
Repeated whitespace \s{2,} Matches two or more consecutive whitespace characters.
Duplicate adjacent word \b(\w+)\s+\1\b Requires backreference support and may need case-insensitive mode.

Transform matched text

Regex Find and Replace

Capture groups make it possible to rearrange or reuse parts of a match in replacement text. Replacement syntax is controlled by the programming language or tool, not only by the regex engine.

Regex replacement references across programming languages
Environment Numbered capture Named capture Example replacement
JavaScript replacement string $1 $<name> $3/$2/$1
Python re.sub() \1 or \g<1> \g<name> \g<3>/\g<2>/\g<1>
Java Matcher.replaceAll() $1 ${name} $3/$2/$1
PCRE-based tools $1 or tool-specific syntax Varies by host application Check the replacement documentation for the tool.

Reformat an ISO-style date

Capture the year, month, and day separately, then reference them in a different order.

^([0-9]{4})-([0-9]{2})-([0-9]{2})$
$3/$2/$1

Swap comma-separated names

Convert text such as Perna, Antonio into Antonio Perna.

^\s*([^,]+),\s*(.+?)\s*$
$2 $1

Collapse repeated whitespace

Replace runs of whitespace with one ordinary space, then trim the beginning and end separately if needed.

\s+

Remove surrounding whitespace

Match whitespace only at the beginning or end and replace each match with an empty string.

^\s+|\s+$

Browser and Node.js patterns

JavaScript Regex Cheat Sheet

JavaScript provides regex literals, the RegExp constructor, and string methods for searching, extracting, replacing, and splitting text.

Interactive JavaScript tool

Test a Regular Expression

Enter a pattern without surrounding slashes. Matches are evaluated locally in your browser using JavaScript.

JavaScript engine
Example: gim

Select “Test regex” to view matches.

Common JavaScript regular expression methods
Method Use Example Copy
RegExp.test() Returns true or false for a match. /^[0-9]+$/.test("2026")
String.match() Returns match information or null. "red blue".match(/\w+/g)
String.matchAll() Returns an iterator containing all matches and capture groups. [..."a1 b2".matchAll(/([a-z])([0-9])/g)]
String.replace() Replaces the first match, or all matches when the regex is global. "a b".replace(/\s+/g, " ")
String.split() Splits a string wherever the regex matches. "red, blue;green".split(/\s*[,;]\s*/)
RegExp.exec() Returns the next detailed match and updates state for global or sticky regexes. /\d+/g.exec("ID 42")

Python re module reference

Python Regex Cheat Sheet

Python’s standard re module provides functions for searching, validating, extracting, replacing, splitting, and compiling regular expressions.

Common Python re module functions and examples
Function Use Example Copy
re.search() Finds the first match anywhere in the string. re.search(r"\d+", "ID 42")
re.match() Checks for a match only at the beginning of the string. re.match(r"[A-Z]+", "ABC-42")
re.fullmatch() Requires the complete string to match the pattern. re.fullmatch(r"[0-9]{5}", "12345")
re.findall() Returns all non-overlapping matches as a list. re.findall(r"\d+", "A1 B22 C333")
re.finditer() Returns an iterator of match objects with positions and groups. re.finditer(r"\w+", "one two")
re.sub() Replaces non-overlapping matches. re.sub(r"\s+", " ", "a b")
re.split() Splits text wherever the pattern matches. re.split(r"\s*[,;]\s*", "red, blue;green")
re.compile() Creates a reusable compiled pattern object. pattern = re.compile(r"^[A-Z]{2}-[0-9]{4}$")

Raw string pattern

Raw strings keep most backslashes intact, making regex patterns easier to read.

pattern = r"\b[A-Z][a-z]+\b"

Named group

Python uses (?P<name>...) for named capturing groups.

r"(?P<year>[0-9]{4})-(?P<month>[0-9]{2})"

Ignore case

Pass flags to a function or compiled pattern to change matching behavior.

re.search(r"\bregex\b", text, re.IGNORECASE)

Java Pattern and Matcher reference

Java Regex Cheat Sheet

Java compiles regular expressions with java.util.regex.Pattern and performs match operations through Matcher.

Common Java Pattern and Matcher methods
Method Use Example Copy
Pattern.compile() Compiles a reusable regular expression. Pattern pattern = Pattern.compile("\\d+");
pattern.matcher() Creates a matcher for the supplied character sequence. Matcher matcher = pattern.matcher("ID 42");
matcher.matches() Requires the complete input region to match. Pattern.compile("\\d+").matcher("42").matches()
matcher.find() Finds the next matching subsequence. while (matcher.find()) { System.out.println(matcher.group()); }
matcher.group() Returns the complete match or a captured group. matcher.group(1)
matcher.replaceAll() Replaces every matching subsequence. matcher.replaceAll("REDACTED")
pattern.split() Splits text around matches of the compiled pattern. Pattern.compile("\\s*[,;]\\s*").split(text)
Pattern.quote() Creates a literal pattern from untrusted or variable text. Pattern.compile(Pattern.quote(userText))

Escaped Java string

Java source code requires two backslashes when the regex engine should receive one.

"\\b[A-Z][a-z]+\\b"

Named group

Java creates a named capturing group with angle-bracket syntax.

"(?<year>[0-9]{4})-(?<month>[0-9]{2})"

Compile with flags

Combine flag constants with the bitwise OR operator when multiple modes are needed.

Pattern.compile("^error:.*$", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE)

Compare regex engines

Regex Flavor Compatibility

Regular expression syntax is not completely portable. Use this comparison to identify common differences between JavaScript, Python’s standard re, Java, PCRE2, and RE2.

Compatibility of regular expression features across common engines
Feature JavaScript Python re Java PCRE2 RE2
Capturing groups Supported Supported Supported Supported Supported
Non-capturing groups (?:...) Supported Supported Supported Supported Supported
Named group (?<name>...) Supported Not this syntax Supported Supported Not this syntax
Named group (?P<name>...) Not supported Supported Not supported Supported Supported
Numbered backreferences Supported Supported Supported Supported Not supported
Positive and negative lookahead Supported Supported Supported Supported Not supported
Lookbehind Supported Fixed-length restrictions Supported with restrictions Supported with configured limits Not supported
Lazy quantifiers Supported Supported Supported Supported Supported
Possessive quantifiers Not supported Python 3.11+ Supported Supported Not supported
Atomic groups (?>...) Not supported Python 3.11+ Supported Supported Not supported
Unicode property escapes \p{...} Supported with Unicode-aware flags Not in standard re Supported Supported Supported
Inline flags such as (?i) Not supported Supported Supported Supported Supported
Absolute end anchor \z Not supported Python 3.14+ Supported Supported Supported

JavaScript

Best for browser and Node.js examples. The interactive tester on this page uses JavaScript behavior.

PCRE2

A feature-rich engine commonly encountered in tools and languages that expose PCRE-compatible matching.

RE2

Prioritizes predictable linear-time matching and intentionally omits backreferences and lookaround assertions.

Avoid excessive backtracking

Regex Performance and ReDoS Safety

Some backtracking regex engines can take unexpectedly long to reject specially constructed input. Keep production patterns constrained, test failure cases, and limit untrusted input.

Regex performance risks and safer approaches
Risk Problematic shape Safer approach Why
Nested overlapping quantifiers (a+)+ a+ Remove redundant repetition when both levels can consume the same text.
Ambiguous alternatives (a|aa)+ a+ Avoid alternatives that match overlapping prefixes when a simpler token works.
Unbounded wildcard .*END [^E]*END when the input rules permit it A more specific class can reduce the number of possible retry positions.
Unanchored validation [A-Z]{2}-[0-9]{4} ^[A-Z]{2}-[0-9]{4}$ Anchors prevent the engine from retrying the validation pattern at later positions.
Unlimited input Large user-controlled strings Enforce a reasonable input-length limit before matching. Even linear work grows with input size, and vulnerable patterns can grow much faster.
Dynamic pattern text Concatenating raw user input into a regex Escape the text or use an engine-provided quoting function. Prevents user text from unexpectedly becoming executable regex syntax.

Test rejection paths

Benchmark long inputs that almost match but fail near the end. These cases often expose backtracking problems more clearly than successful matches.

Use runtime limits

Where the platform allows it, apply match timeouts, request limits, cancellation, or isolation when patterns run against untrusted data.

Choose the right engine

RE2 intentionally excludes constructs that require backtracking, including backreferences and lookarounds, to provide predictable matching time.

Common regular expression questions

Regex Frequently Asked Questions

Quick answers to common questions about writing, testing, debugging, and safely using regular expressions.

What is regex?

Regex, short for regular expression, is a pattern language used to search, extract, validate, split, or replace text. Regex syntax is interpreted by an engine built into a programming language or tool.

What is the difference between regex and RegExp?

Regex is the common abbreviation for regular expression. RegExp often refers to a programming-language object or class, such as JavaScript’s RegExp constructor.

Why does my regex work in one tool but fail in another?

The tools may use different regex engines, versions, default modes, Unicode rules, delimiters, or string-escaping requirements. Confirm the exact flavor and API before transferring a pattern.

How do I match an entire string?

Use a full-match API when one is available. Otherwise, start and end anchors such as ^pattern$ are commonly used, with attention to multiline behavior and engine-specific end anchors.

Why does .* match too much?

The * quantifier is greedy by default. Use a more specific character class when possible, or a lazy form such as .*? when the engine supports it and the surrounding pattern provides a clear stopping point.

Can regex fully validate an email address?

A regex can perform a useful format check, but reliable validation normally also requires application rules and a verification step such as sending a confirmation message. Avoid enormous patterns that attempt to model every theoretical address form.

When should I escape a character?

Escape a regex metacharacter when you need its literal meaning. In source code, you may also need to escape the backslash for the programming language’s string syntax.

How should I debug a regex?

Reduce the pattern to the smallest failing part, test one construct at a time, inspect captured groups, confirm the flags, and use sample inputs that should both match and fail.

What is catastrophic backtracking?

It occurs when a backtracking engine explores a very large number of possible matching paths before succeeding or failing. Ambiguous nested quantifiers are a common warning sign.

Is the interactive tester safe for private text?

The tester provided on this page evaluates the pattern locally in the visitor’s browser and does not need to send the test text to a server. Visitors should still avoid pasting secrets into unfamiliar third-party tools.

Leave a Comment