EUComply

Regex Cheat Sheet — Complete Reference

Every regex metacharacter, anchor, quantifier, group, and lookaround — with practical examples. Test any pattern live with our interactive regex tester.

Jump to Practical Patterns

1. Anchors

Anchors don't match characters — they match positions in the string. They assert where a match can start or end.

TokenNameMeaningExample
^Start anchorStart of string (or line in multiline mode)^Hello matches "Hello" only at the start
$End anchorEnd of string (or line in multiline mode)world$ matches "world" only at the end
\bWord boundaryPosition between word and non-word char\bcat\b matches "cat" but not "catalog"
\BNon-word boundaryPosition NOT at a word boundary\Bcat matches "cat" in "catalog" but not " cat "

Examples

^[A-Z] — Lines starting with a capital letter

\d$ — Lines ending with a digit

\b\w{6}\b — Exactly six-letter words

2. Quantifiers

Quantifiers say how many of the preceding token to match. By default they are greedy — they match as much as possible.

TokenNameMeaningGreedy?
*Star / Kleene star0 or moreGreedy
+Plus1 or moreGreedy
?Optional0 or 1Greedy
{n}ExactExactly n times
{n,}At leastn or moreGreedy
{n,m}RangeBetween n and m timesGreedy
*?Lazy star0 or more — as few as possibleLazy
+?Lazy plus1 or more — as few as possibleLazy
??Lazy optional0 or 1 — prefers 0Lazy

Greedy vs Lazy — Critical Difference

Text: "foo" "bar" "baz"

".+" (greedy) → matches "foo" "bar" "baz" — takes everything between first and last quote

".+?" (lazy) → matches "foo", "bar", "baz" — stops at each closing quote

3. Escape Sequences — Shortcuts

TokenMeaningNegation
\dDigit [0-9]\D — non-digit
\wWord char [a-zA-Z0-9_]\W — non-word char
\sWhitespace [ \t\n\r\f\v]\S — non-whitespace
\tTab
\nNewline (LF)
\rCarriage return (CR)
\\Literal backslash
\.Literal period (use \. not .)
\xNNHex escape (e.g. \x20 = space)
\\uNNNNUnicode escape (JS: \\u00e9 = é)
Remember: . (dot) matches any character except newline unless the s (dotall) flag is set. Always escape it as \. when matching a literal period.

4. Character Classes

PatternMeaningExample
[abc]Any one of a, b, or cgr[ae]y matches "gray" or "grey"
[^abc]NOT a, b, or c[^0-9] matches any non-digit
[a-z]Range: a through z[A-Za-z] any letter
[a-zA-Z0-9_]Same as \wWord character
[0-9]Same as \dDigit
[.-.]Escaped metachar inside class[.\-\[\]] matches ., -, or [
[&&]Intersection (Java)[a-z&&[^aeiou]] consonants

Tips

Most metacharacters lose their special meaning inside [...] — only \, ^ (if first), and - (if between two chars) need escaping.

q[^u] matches "q" followed by anything except "u" — useful for languages where "q" is always followed by "u".

5. Groups and Captures

TokenNameDescription
(...)Capturing groupGroups a pattern AND captures the matched text. Referenced by \1, \2 (backreference) or $1, $2 (replacement).
(?:...)Non-capturing groupGroups a pattern but does NOT capture. No backreference created.
(?P>name>...)Named capture (Python)Captures with a name. Reference: (?P=name) or \k<name>
(?<name>...)Named capture (.NET, JS, Ruby)Captures with a name. JS: $<name> in replace.
(?P=name)Named backreferenceMatches same text as the named group
\1 .. \9Numeric backreferenceMatches exact same text as group #1..9 earlier in the pattern
(?(cond)yes|no)ConditionalIf group cond matched, try yes; otherwise try no

Backreference Example

(["']).*?\1 — Matches a quoted string with matching opening/closing quote. \1 must be the same character that group 1 captured (either " or ').

Works on: "hello", 'world' — but NOT on "broken'

Non-capturing Group Example

(?:\d{3}-){2}\d{4} — Matches 555-123-4567 without storing the area code

6. Lookarounds

Lookarounds are zero-width assertions that check what is (or isn't) ahead or behind the current position — without consuming characters.

TokenNameMatches
(?=...)Positive lookaheadPosition followed by ...
(?!...)Negative lookaheadPosition NOT followed by ...
(?<=...)Positive lookbehindPosition preceded by ...
(?<!...)Negative lookbehindPosition NOT preceded by ...

Lookahead Examples

\d+(?= dollars) — matches "100" in "100 dollars" but not "100 euros"

(?!.*\.exe$).+ — file names NOT ending in .exe

Lookbehind Examples

(?<=USD )\d+ — matches "50" in "USD 50" but not "EUR 50"

(?<!@)\w+ — words NOT preceded by @ (avoid matching usernames)

Combined — Password Validation

^(?=.*[a-z])(?=.*[A-Z])(?=.*\d).{8,}$

Matches strings with at least 8 chars containing lowercase, uppercase, and a digit. Each lookahead checks a condition independently.

7. Flags (Modifiers)

Flags change how the entire regex behaves. In JavaScript, they follow the pattern: /pattern/flags.

FlagNameEffect
gGlobalFind all matches, not just the first
iCase-insensitiveTreat a and A as the same
mMultiline^ and $ match line boundaries, not just string boundaries
sDotall. matches newline characters as well
uUnicodeEnables \u{...} escapes and treats the string as Unicode code points
yStickyOnly matches from lastIndex (no scanning ahead)

Practical Flag Combinations

/hello/i — matches "Hello", "HELLO", "hello", "hElLo"

/^[A-Z]/gm — matches every line that starts with a capital letter

/

.*?<\/div>/gs — matches <div> blocks spanning multiple lines

8. Common Practical Patterns

Ready-to-use regex patterns for real-world tasks. Test any of these live with our interactive regex tester.

Email Address

Validates most common email formats.

^[\w\.-]+@[\w\.-]+\.\w{2,}$

URL / Link

Matches http/https URLs with optional www.

https?:\/\/(www\.)?[-a-zA-Z0-9@:%._\+~#=]{1,256}\.[a-z]{2,6}\b([-a-zA-Z0-9@:%_\+.~#?&//=]*)

IPv4 Address

Matches four-part decimal IP.

^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$

Phone Number (US)

Matches (123) 456-7890, 123-456-7890, etc.

^\(?\d{3}\)?[-.\s]?\d{3}[-.\s]?\d{4}$

Date (ISO 8601)

Matches YYYY-MM-DD format with validation.

^\d{4}-(?:0[1-9]|1[0-2])-(?:0[1-9]|[12]\d|3[01])$

HTML Tag

Matches opening or self-closing HTML tags.

<\/?[\w-]+(?:\s[^>]*)?\/?>

Strong Password

8+ chars, upper, lower, digit, special.

^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[!@#$%^&*()_\-+=]).{8,}$

UUID / GUID

Standard 36-char hex UUID.

^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$

MAC Address

Colon- or dash-separated hex pairs.

^([0-9a-f]{2}[:-]){5}[0-9a-f]{2}$

Hex Color

#fff or #ffffff format.

^#([0-9a-f]{3}|[0-9a-f]{6})$

Slug (URL-friendly)

Lowercase letters, digits, hyphens.

^[a-z0-9]+(?:-[a-z0-9]+)*$

Credit Card (generic)

16 digits with optional spaces/dashes.

^\d{4}[\s-]?\d{4}[\s-]?\d{4}[\s-]?\d{4}$

Extract Domain from URL

Captures the domain portion.

https?:\/\/([^\/\n]+)

Whitespace Trim

Leading and trailing whitespace.

^\s+|\s+$

Duplicate Words

Finds adjacent duplicate words.

\b(\w+)\s+\1\b

Base64 Encoded

Standard base64 string validation.

^[A-Za-z0-9+/]+={0,2}$

Semantic Version (SemVer)

v1.2.3 or 1.2.3 with pre-release.

^v?\d+\.\d+\.\d+(?:-[0-9a-z-]+)?$

Time (HH:MM 24h)

Validates 00:00 through 23:59.

^(?:[01]\d|2[0-3]):[0-5]\d$

Social Security (US)

XXX-XX-XXXX with valid area numbers.

^(?!000|666)\d{3}-(?!00)\d{2}-(?!0000)\d{4}$

Git Commit Hash

Full 40-char hex SHA or short 7-chars.

^[0-9a-f]{7,40}$

Youtube Video ID

Extract video ID from any YouTube URL.

(?:youtu\.be\/|youtube\.com\/(?:v\/|embed\/|watch\?v=))([\w-]{11})

CSS Class/ID Selector

Matches valid CSS identifiers.

^\.-?[_a-zA-Z][_a-zA-Z0-9-]*$

9. Advanced Techniques

Recursive Patterns

Some engines (PCRE, Ruby) support recursive matching for nested structures:

/\((?:[^()]|(?R))*\)/   # Matches nested parentheses
/\((?:[^()]|(?0))*\)/   # Same, alternative syntax

Atomic Groups

An atomic group (?>...) prevents backtracking. Use it to fail faster and avoid catastrophic backtracking:

(?>\d+)[a-z]   # If no lowercase after digits, fail immediately
               # instead of backtracking through every digit

Possessive Quantifiers

Like greedy but NEVER gives back characters — same effect as atomic groups:

\d++[a-z]   # Possessive plus — never backtracks
\d*+[a-z]   # Possessive star
\d?+[a-z]   # Possessive optional
Catastrophic Backtracking Warning: Patterns like (a+)+b or (x+x+)+y can lock up the engine on near-matches. Use atomic groups or possessive quantifiers to prevent this. Our regex tester catches this and shows the error.

In-Engine Flags

Toggle flags mid-pattern with inline modifiers:

(?i)case-insensitive   # Turn on case-insensitivity from this point
(?-i)case-sensitive    # Turn it off
(?i:insensitive only)  # Only this part is case-insensitive
(?x)                   # Free-spacing mode (ignore whitespace and comments)

Balanced Groups (.NET)

.NET supports balanced groups for counting opening/closing delimiters:

(?'open'<)(?:[^<>]|(?'open'<)|(?'-open'>))*(?(open)(?!))>

Test These Patterns Live

Copy any pattern from this cheat sheet into our interactive regex tester. See matches highlight in real time, inspect capture groups, and try substitutions.

Open Regex Tester →