Regex Cheatsheet: Common Patterns with Practical Examples

Quick Reference: Symbols and Meaning

Symbol Meaning Example
. Any single char (except newline) a.c → abc, a1c
* 0 or more of preceding ab* → a, ab, abbb
+ 1 or more of preceding ab+ → ab, abbb
? 0 or 1 of preceding colou?r → color, colour
{n} Exactly n times \d{4} → 2025
{n,m} n to m times \d{2,4} → 12, 123, 1234
^ Start of string ^Hello
$ End of string world$
[...] Character set [aeiou] matches any vowel
[^...] Negated set [^0-9] matches non-digits
\d Digit [0-9] \d+ → 123
\w Word char [A-Za-z0-9_] \w+ → hello_1
\s Whitespace space, tab, newline
(...) Capturing group Extract matched portion
(?:...) Non-capturing group Group without capture
(?=...) Positive lookahead Assert ahead without consuming
(?!...) Negative lookahead Assert ahead does not match

Common Validation Patterns

Use case Pattern What it guarantees
Email ^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$ Common email shape; not the full RFC 5322 grammar
Phone (China mainland) ^1[3-9]\d{9}$ 11 digits starting with 1, second digit 3-9; not +86, spaces, or dashes
URL ^https?:\/\/(www\.)?[-a-zA-Z0-9@:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()@:%_\+.~#?&//=]*)$ Common http/https shape
IPv4 `^(?:(?:25[0-5] 2[0-4]\d
IPv6 (simplified) ^([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}$ Full eight-group form; no :: compression
Date YYYY-MM-DD `^\d{4}-(0[1-9] 1[0-2])-(0[1-9]
Hex color `^#?([0-9a-fA-F]{3} [0-9a-fA-F]{6})`
Password strength ^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)[A-Za-z\d@$!%*?&]{8,}$ 8+ chars with upper, lower, digit
China ID (18 digit) `^[1-9]\d{5}(19 20)\d{2}(0[1-9]
Extract links https?:\/\/[^\s]+ Stops at whitespace; trailing punctuation is swallowed

Email: Loose Beats Strict

The full RFC 5322 pattern runs to thousands of characters, is painful to maintain, and still cannot answer whether a mailbox exists. The pattern above covers 99% of common addresses and catches obvious typos such as a missing @, a domain with no dot, or a one-letter TLD.

Failure is concrete: tighten the character set and legitimate rare addresses get rejected; loosen it to [^\s@]+@[^\s@]+ and a@b passes. The only real verification is a confirmation email — a link click or a code. Here the regex is a filter, not proof.

Phone: Format Filter Only

^1[3-9]\d{9}$ says exactly three things: starts with 1, second digit 3-9, eleven digits total. It does not cover +86 138... or 138-xxxx-xxxx, and it cannot tell whether a prefix has actually been allocated. Prefix ranges change with regulation, so any pattern that hardcodes them will eventually reject valid new numbers.

For international numbers use Google's libphonenumber, which ships national numbering plans. Hand-written regex cannot.

IPv4 and IPv6: Do Not Hand-Roll Full Validation

The IPv4 pattern looks dense but does one thing: each octet must be 0-255. 25[0-5] covers 250-255, 2[0-4]\d covers 200-249, 1\d\d covers 100-199, [1-9]?\d covers 0-99, repeated four times.

IPv6 is hard not because of characters but because of :: compression: 2001:db8::1 omits runs of zero groups, and a naive pattern either accepts too much or rejects valid forms. In production use a library such as ipaddress or the platform parser.

Date and ID: Shape Is Not Validity

The date pattern only checks "four digits, two digits, two digits". 2025-02-30 passes, because February's length depends on the year. Parse with a date library to reject impossible dates.

The ID pattern similarly checks a 6-digit region code, a 19xx/20xx year, month and day ranges, a 3-digit sequence, and a final digit-or-X. It cannot compute whether the check digit is correct. For strict validation, calculate the weighted sum and compare; for a form pre-filter, this is enough.

Greedy vs Lazy: The Root of Over-Matching

Quantifiers are greedy by default: take as much as possible, then give characters back one at a time on failure. Against <div>text</div>:

<.*>   →  <div>text</div>     # runs to the last >
<.*?>  →  <div>                # ? makes it lazy: stops at the first >

The symptom is "the pattern is right but the match is huge", common with HTML tags, quoted strings, and log extraction. Diagnosis: look at the highlighted span in a tester; if it crosses the terminator you wanted, greediness is the cause. Fix it with ?, or better, state what cannot appear — "[^"]*" is far safer than ".*".

Calling Regex from Each Language

JavaScript

const emailRegex = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;
const isValid = emailRegex.test('user@example.com'); // true
const matches = 'Visit https://example.com and https://oltools.com'
  .match(/https?:\/\/[^\s]+/g);

Python

import re
email_re = r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$'
is_valid = bool(re.match(email_re, 'user@example.com'))
urls = re.findall(r'https?://[^\s]+', 'Visit https://example.com')

Three Rules for Production

  • Pre-compile, capture less: compile once outside loops; use (?:...) for groups you never read.
  • Anchor and test edges: add ^/$ for whole-string matching; try empty, very long, and Unicode input.
  • Never parse HTML/XML: nested structure exceeds what regex can express; use a parser.

Nested quantifiers also backtrack exponentially on bad input — see catastrophic backtracking.

Reproducible Results

import re
re.findall(r'\d{4}-\d{2}-\d{2}', 'from 2025-04-20 to 2025-05-01')
# → ['2025-04-20', '2025-05-01']
re.findall(r'[\w.+-]+@[\w-]+\.[\w.]+', 'a@b.com, x.y+tag@sub.example.io')
# → ['a@b.com', 'x.y+tag@sub.example.io']

Note the second call on a@b.com,: the comma is outside the character class, so it never enters the domain. Saying what a character class allows beats trimming the result afterwards.

Online Validation

  • regex101.com: highlighted matches, per-token explanation, engine switching
  • regexr.com: interactive editing and reference
  • This site's regex tester: paste a pattern and samples, see the matched span

Frequently Asked Questions

What is the difference between greedy and lazy matching?

Quantifiers are greedy by default and match as much as possible. Against <div>text</div>, the pattern <.*> runs all the way to the final >; the lazy form <.*?> matches only <div>. Adding ? after a quantifier switches it to lazy. Overusing greedy quantifiers is the number one reason a regex matches far more than intended. The [regex tester](/regex-tester.html) highlights the matched span so you can see it.

Why does my regex suddenly hang?

Almost certainly catastrophic backtracking. With nested quantifiers such as (a+)+$, a long non-matching input forces the engine to try an exponential number of combinations, pinning the CPU. Defend by avoiding nested quantifiers, using atomic groups or possessive quantifiers where the engine supports them, and capping input length. Never run a regex without a timeout over user-controlled input — that is a textbook ReDoS surface.

When should I use capturing versus non-capturing groups?

(...) is a capturing group: it stores the match in the results array, costing memory and consuming a numbered slot. (?:...) is non-capturing: it groups without saving. The rule is simple — capture only what you intend to extract; use a non-capturing group for grouping or applying a quantifier. Named groups (?<name>...) also read far better than positional indexes and survive refactoring without shifting.

How strict should an email or phone regex be?

Loose is better than strict. The full RFC 5322 email regex runs to thousands of characters and still cannot verify that a mailbox exists; phone number ranges change with regulation, so hardcoding them guarantees false rejections. A sane approach: use a permissive format filter (for email, check that there is an @ with non-empty sides) to catch obvious typos, then verify for real by sending a confirmation email or SMS code. Let the regex reject the 99% of garbage, not prove correctness.

← Back to Blog