PRACTICAL METHODFrom syntax to a dependable result
01Write the validation goal first
Before writing a regex, describe the accepted shape and rejection boundaries in plain sentences. For phone, email, or identity-like fields, character shape is only one layer; length, country or institutional rules, and ownership checks remain separate.
02Test small and opposing fixtures
Prepare at least one expected match, one expected rejection, and one long or malformed input. With the global flag, inspect all matches and lastIndex behavior; for multiline text, test the effects of m and s independently.
03Acceptance check before production
Run the pattern again in the target runtime and include Unicode characters and unexpected line endings. Bound user-supplied patterns, and never treat a pattern as a security boundary until nested quantifiers have been measured against adversarial long input.
04Know when a parser is the right tool
One regex is not a dependable parser for nested JSON, HTML, programming languages, free-form postal addresses, or an entire email standard. Use the relevant parser or domain library first and reserve regex for a narrow, disclosed pre-check.
01
Core building blocks
| Syntax | Meaning | Example |
|---|
. | Any single character except a line break | a.c |
\d / \D | Digit / non-digit | \d{4} |
\w / \W | ASCII word character / inverse | \w+ |
[a-z] / [^a-z] | Range / negated character class | [A-F0-9] |
^ / $ | Start / end of input or line | ^OK$ |
02
Repetition and grouping
| Syntax | Meaning | Example |
|---|
* / + / ? | Zero-or-more / one-or-more / optional | https? |
{n} / {n,m} | Exact or ranged repetition | \d{2,4} |
(abc) / (?:abc) | Capturing / non-capturing group | (?:png|webp) |
(?<name>...) | Named capture group | (?<year>\d{4}) |
(?=...) / (?!...) | Positive / negative lookahead | \d+(?=px) |
03
JavaScript flags
| Syntax | Meaning | Example |
|---|
g | Find all matches rather than stopping at the first | — |
i | Case-insensitive matching | — |
m | Make ^ and $ operate per line | — |
s | Allow . to match line breaks | — |
u / v | Unicode modes; check engine support | — |
FAQCommon questions
Can regex validate an email address?+
Regex checks only a format candidate. Deliverability and ownership require a verification email.
What is ReDoS risk?+
Poorly designed nested quantifiers can cause extreme backtracking. Bound input, test patterns, and isolate untrusted expressions.