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?rmatches 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|birdmatches 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:
- Never nest quantifiers inside other quantifiers (e.g. avoid
(x+)+). - Use atomic grouping or possessive quantifiers where supported (e.g.
*+or++). - 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,}$