Regular Expressions (Regex) Cheat Sheet: Syntax & Practical Guide

Discover the complete regex cheat sheet for beginners and developers. Learn regular expression syntax, character classes, quantifiers, anchors, groups, flags, and useful patterns for email validation, phone numbers, text extraction, and more.

Use the matching Expeditious Tools utility: Regex Generator & Tester →

regex cheat sheet Banner
regex cheat sheet Banner

In modern computer science and software development, Regular Expressions (Regex) provide a formal, algebraic syntax for pattern matching, string searching, lexical analysis, and data validation. Conceived in the 1950s by mathematician Stephen Cole Kleene to describe regular languages in automata theory, regular expressions are now natively integrated into virtually every programming language, text editor, and Unix command-line utility.

Whether you are parsing server log files, validating user registration inputs, building URL routing engines, or scraping web documents, having a fast, reliable syntax reference is indispensable. This comprehensive cheat sheet and technical guide covers the essential metacharacters, quantifiers, grouping constructs, assertions, and security hazards of modern regular expressions.

1. Anchors & Boundaries: Matching Positions

Anchors do not match actual characters; instead, they assert that the current search position corresponds to a specific structural boundary within the string:

Metacharacter Boundary Description Example & Behavior
^ Beginning of string (or line with m flag) ^Order matches "Order #12" but not "Purchase Order"
$ End of string (or line with m flag) \.pdf$ matches "doc.pdf" but not "doc.pdf.bak"
\b Word boundary (transition between \w and \W) \bcat\b matches "cat" in "the cat sat", but ignores "category"
\B Non-word boundary \Bcat matches "scatter" or "locate", but not standalone "cat"

2. Character Classes & Shorthand Metacharacters

Character classes match a single character from a defined set or range:

Symbol Class Definition Equivalent Expression
. Any character except newline (matches newline with s flag) [^ ]
\d Any ASCII digit [0-9]
\D Any non-digit character [^0-9]
\w Word character (alphanumeric and underscore) [a-zA-Z0-9_]
\W Non-word character [^a-zA-Z0-9_]
\s Whitespace character (space, tab, carriage return, newline) [ ]
\S Non-whitespace character [^ ]
[a-z] Any lowercase character between 'a' and 'z' Custom inclusive range
[^a-z] Negated character class (any character except lowercase letter) Custom exclusive range

3. Quantifiers: Greedy, Lazy, and Exact Bounds

Quantifiers define how many times the preceding element or group can repeat:

  • *: Zero or more occurrences (greedy). a* matches "", "a", "aaa".
  • +: One or more occurrences (greedy). a+ matches "a", "aaa", but not empty string.
  • ?: Zero or one occurrence (optional flag). colou?r matches both "color" and "colour".
  • {n}: Exactly n repetitions. \d{4} matches exactly a 4-digit year.
  • {n,}: At least n repetitions. \w{8,} matches strings of 8 or more characters.
  • {n,m}: Between n and m repetitions inclusive. \d{2,4} matches 2, 3, or 4 digits.

Greedy vs. Lazy Matching

By default, quantifiers in regular expressions are greedy: they consume as much text as possible while still allowing the overall pattern to match. Adding a question mark ? after any quantifier converts it into a lazy (non-greedy) quantifier, consuming as few characters as possible:

Sample String: <b>First</b> and <b>Second</b>

Greedy Match (<b>.*</b>):  "<b>First</b> and <b>Second</b>"  (1 huge match)
Lazy Match   (<b>.*?</b>): "<b>First</b>" and "<b>Second</b>"  (2 distinct matches)

Build & Test Regular Expressions Online

Need to generate tested regex patterns, highlight matches in real-time, or export copyable code for JavaScript, PHP, and Python? Use our free browser-based utility:

Launch Free Regex Generator & Tester →

4. Capturing Groups, Non-Capturing Groups, & Alternation

Parentheses serve two critical functions in regex: applying quantifiers to multi-character sub-expressions, and extracting matched fragments for subsequent processing:

  • Capturing Group (...): Groups tokens and saves the matched text in numbered memory slots (Group 1, Group 2). Example: (\d{4})-(\d{2})-(\d{2}) captures Year, Month, and Day as separate accessible variables.
  • Non-Capturing Group (?:...): Groups tokens without consuming memory or polluting capture indexes. Example: (?:https?|ftp):// matches protocols without storing the match.
  • Alternation |: Functions as a boolean OR operator. cat|dog|bird matches any one of the specified terms.

5. Lookahead and Lookbehind Assertions (Zero-Width Matches)

Lookarounds match a character or pattern only when it is followed or preceded by another pattern, without including the surrounding pattern in the matched output:

Assertion Type Syntax Operational Meaning & Example
Positive Lookahead (?=...) Matches only if followed by pattern. \d+(?= USD) matches "100" in "100 USD" (excludes " USD").
Negative Lookahead (?!...) Matches only if NOT followed by pattern. \d+(?! px) matches "50" in "50 rem", but ignores "50 px".
Positive Lookbehind (?<=...) Matches only if preceded by pattern. (?<=$)\d+ matches "45" in "$45" (excludes "$").
Negative Lookbehind (?<!...) Matches only if NOT preceded by pattern. (?<!\)$ matches unescaped dollar signs.

6. Catastrophic Backtracking (ReDoS) and Performance Hazards

A major vulnerability in web applications is Regular Expression Denial of Service (ReDoS). ReDoS occurs when a pattern with nested quantifiers (such as (a+)+$ or ([a-zA-Z0-9]+)*$) is evaluated against a malformed string that nearly matches but fails at the very end.

The regex backtracking engine attempts every conceivable combination of inner and outer repetitions, leading to an exponential complexity of O(2N). On a string of just 30 characters, the engine may attempt over 1,000,000,000 permutations, locking CPU cores and crashing web server worker processes.

To prevent ReDoS:

  1. Never nest quantifiers inside other quantifiers (e.g. avoid (x+)+).
  2. Use atomic grouping or possessive quantifiers where supported (e.g. *+ or ++).
  3. Enforce maximum length boundaries on raw user inputs before passing them into regex engines.

7. Production Regex Patterns Reference

Below is a curated reference matrix of battle-tested regular expressions for common web engineering tasks:

Standard Email (RFC 5322 Practical):
^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$

Website URL (HTTPS / HTTP with optional query strings):
^https?:\/\/(?:www\.)?[-a-zA-Z0-9@:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()@:%_\+.~#?&//=]*)$

International Telephone (E.164 Format):
^\+[1-9]\d{1,14}$

IPv4 Dotted-Decimal Address:
^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$

UUID v4 (Universally Unique Identifier):
^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$

ISO-8601 Date (YYYY-MM-DD):
^\d{4}-(?:0[1-9]|1[0-2])-(?:0[1-9]|[12]\d|3[01])$

Strong Password (Min 8 chars, 1 uppercase, 1 lowercase, 1 digit, 1 special symbol):
^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{8,}$
Share this article:

Continue reading more tutorials and guides

Common JSON syntax errors and how developers can fix invalid JSON Developer Utilities & Code

Common JSON Errors and How to Fix Them: A Developer's Guide

JSON syntax errors can interrupt API requests, break applications, and cause frustrating parsing problems. This developer's guide explains 15 common JSON errors and how to fix them, including missing commas, trailing commas, incorrect quotation marks, unmatched brackets, invalid data types, unexpected token errors, and JSON parsing errors. Learn how to validate JSON online, format JSON correctly, troubleshoot JavaScript and PHP errors, and prevent common mistakes in your development projects.

Muhammad Noman Muhammad Noman
25 min read
25 useful regex patterns and regular expression cheat sheet for developers Developer Utilities & Code

25 Useful Regex Patterns Every Developer Should Know

Discover 25 useful regex patterns every developer should know. This practical guide covers email validation regex, URL validation regex, password checks, phone numbers, dates, IP addresses, file extensions, JavaScript regex examples, common regex syntax, flags, and a complete regular expression cheat sheet. Learn how to test, debug, and use regular expressions effectively in your development projects.

Muhammad Noman Muhammad Noman
22 min read
Meta title and meta description SEO optimization guide SEO & Search Marketing

Meta Title vs Meta Description: Key SEO Differences Explained

Learn the difference between meta titles and meta descriptions and discover how to optimize both for better search visibility. This complete SEO guide covers recommended title length, meta description best practices, keyword placement, practical examples, HTML implementation, Laravel integration, Open Graph tags, common mistakes, and tips for improving your website's appearance in Google search results.

Muhammad Noman Muhammad Noman
26 min read