A regular expression (regex) is a compact pattern language for searching, validating, and transforming text: finding every ISO date in a server log, extracting order IDs from emails, cleaning messy pasted lists, or swapping date formats from DD/MM/YYYY to YYYY-MM-DD. Regex looks intimidating because it packs a lot of meaning into punctuation, yet roughly fifteen building blocks cover 95% of real-world engineering and data work. This guide teaches each building block step by step with examples you can test live in SnipFerry’s Regex Tester.
Literals and metacharacters
Ordinary letters and digits match themselves literally: cat matches “cat”. Twelve punctuation characters have special meaning in regex and must be escaped with a backslash (\) when you want the literal character: . * + ? ^ $ ( ) [ ] { } | \. For example, 3.5 matches “3.5”, “3x5”, and “3 5” because . means “any character”, whereas 3\.5 matches only literal “3.5”.
Character classes and anchors
| Token | Matches | Example |
|---|---|---|
. | Any character except newline (unless s flag is set) | c.t → cat, cut, c9t |
\d / \D | Any ASCII digit (0-9) / any non-digit | \d{4} → 2026 |
\w / \W | Word char (A-Za-z0-9_) / non-word char | \w+ → user_42 |
\s / \S | Any whitespace (space, tab, newline) / non-whitespace | \s+ → runs of spaces |
[aeiou] | One character from the listed set | gr[ae]y → gray or grey |
[^0-9] | Negated set: any character NOT in the brackets | [^,]+ → CSV field without commas |
^ / $ | Start / end of string (or each line with m flag) | ^ERROR: → lines starting with ERROR: |
\b | Word boundary between \w and \W | \bcat\b → “cat” but not “catalog” |
a|b | Alternation: either left or right branch | (jpg|png|webp) |
Quantifiers: greedy vs lazy matching
| Quantifier | Meaning | Example |
|---|---|---|
* | 0 or more times | \s* optional spaces |
+ | 1 or more times | \d+ one or more digits |
? | 0 or 1 time (optional) | https?:// http or https |
{n} | Exactly n times | \d{6} 6-digit Indian PIN code |
{n,} | At least n times | [A-Z]{2,} two or more caps |
{n,m} | Between n and m times | \d{2,4} |
By default, quantifiers are greedy — they consume as much text as possible. On the string "<b>one</b> and <b>two</b>", the greedy pattern <.+> swallows everything from the first < to the very last > as one giant match. Appending ? makes the quantifier lazy (<.+?>), or even better and faster, use a negated character class (<[^>]+>) which matches each tag cleanly with zero backtracking.
Capture groups, named groups, and replacements
Parentheses (…) serve two jobs: grouping tokens for quantifiers/alternation, and capturing the matched substring so you can extract or reorder it in a replacement:
Input: "Invoice dated 29/10/2026 (ref #INV-408)"
Pattern: (\d{2})/(\d{2})/(\d{4})
Replacement: $3-$2-$1
Result: "Invoice dated 2026-10-29 (ref #INV-408)"
- Non-capturing groups
(?:…): Group without polluting numbered captures:(?:https?://)([^/]+)keeps the domain cleanly in$1. - Named capture groups
(?<name>…): Self-documenting patterns like(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})let you reference$<year>in replacements andmatch.groups.yearin JavaScript. - Backreferences
\1: Match repeated words like\b(\w+)\s+\1\b(catches accidental “the the” typos!).
Lookahead and lookbehind assertions
Sometimes you want to match text only when it is followed or preceded by something else without including that context in the match:
- Positive lookahead
(?=…):\d+(?=\s*USD)matches the number500in"500 USD"without capturing “USD”. - Negative lookahead
(?!…):foo(?!bar)matches “foo” only when not immediately followed by “bar”. - Positive lookbehind
(?<=…):(?<=₹)\d[\d,]*extracts1,250from"₹1,250"without the currency symbol.
Flags every developer uses
g(global) — find every match in the input instead of stopping at the first.i(ignoreCase) — match uppercase and lowercase letters identically.m(multiline) — make^and$match the start and end of every line, not just the whole document.s(dotAll) — allow.to match newline characters.u(unicode) — handle multi-byte emoji, astral characters, and Unicode property escapes such as\p{L}(any letter in any language, including Devanagari and accented Latin).
Copy-ready practical patterns
| Task | Pattern | Flags |
|---|---|---|
| ISO 8601 date (YYYY-MM-DD) | \b\d{4}-(?:0[1-9]|1[0-2])-(?:0[1-9]|[12]\d|3[01])\b | g |
| Trailing spaces/tabs at line end | [ \t]+$ | gm |
| Empty or whitespace-only lines | ^[ \t]*\r?\n | gm |
| Indian 6-digit PIN code | \b[1-9]\d{5}\b | g |
| Hex colour (3 or 6 digits) | #(?:[0-9a-fA-F]{3}){1,2}\b | g |
| Semantic version (e.g. 2.14.0) | \bv?\d+\.\d+\.\d+(?:-[\w.-]+)?\b | g |
| Practical email shape check | ^[^\s@]+@[^\s@]+\.[^\s@]+$ | — |
| UUID (v1–v7) | \b[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\b | gi |
Notice the email pattern is intentionally simple. RFC 5322 allows obscure quoted addresses that no regex handles cleanly; check the basic local@domain.tld shape, then confirm deliverability with a verification link.
Four regex pitfalls that break production systems
- Missing anchors on validation. Checking
/\d{6}/returns true on"order-999999999"because six digits appear inside nine. Always wrap full-field validators with^…$(or\b…\bwhen extracting from prose). - Catastrophic backtracking (ReDoS). Nested ambiguous quantifiers like
(a+)+$or(\w+\s?)+$cause exponential CPU spikes on non-matching input, freezing a Node.js event loop or server thread. Replace overlapping nested quantifiers with atomic negated classes ([^…]+) and cap input lengths. - Dialect differences. JavaScript, Python (
re), Go (RE2, which bans lookarounds and backreferences to guarantee linear time), PCRE, and POSIXgrepdiffer in syntax. SnipFerry’s Regex Tester runs your browser’s real JavaScript RegExp engine. - Parsing nested HTML, XML, or JSON with regex. Regular expressions cannot reliably balance arbitrary nested tags or escaped quotes. Use a real parser (JSON Validator, DOMParser, or an HTML sanitiser) instead.
For bulk regex search-and-replace across a document, open Find and Replace with RegEx mode switched on, or follow the full text-cleaning sequence in How to Clean Up Messy Text.