Regular expressions: a practical guide with tested examples
Updated 11 October 2026 · 5 min read
regexdeveloperpatternsjavascript
A regular expression (regex) is a short pattern that describes a set of strings. You use it to find text, check that input has the right shape, pull values out of a log line or rewrite many strings in one pass. The syntax looks dense at first, but it is built from a small number of ideas that combine.
This guide covers those ideas in JavaScript flavour, since that is what browsers and Node.js use. Every pattern in the worked examples was run against its sample text, and the matches shown are the real output. You can paste any of them into a regex tester to experiment.
Literals, classes and quantifiers
Most characters match themselves: cat finds the letters c, a, t in a row. A character class in square brackets matches one character out of a set, so [aeiou] matches any vowel and [0-9] any digit. Shortcuts cover common sets: \d is a digit, \w a letter, digit or underscore, \s whitespace, and . almost any character except a line break. Capital versions (\D, \W, \S) mean the opposite.
A quantifier says how many times the thing before it may repeat: ? is zero or one, * zero or more, + one or more, {4} exactly four, {2,5} two to five. So \d{4} is four digits and colou?r matches both spellings.
Characters with special meaning, such as . * + ? ( ) [ ] { } | ^ $ \, need a backslash to be taken literally. To match a full stop, write \..
Anchors, groups and alternation
Anchors match a position rather than a character. ^ is the start and $ the end of the text (or of each line with the m flag), and \b is a word boundary. Compare \bcat\b with plain cat: run with the gi flags on "Cat catalog cat." it matches "Cat" and "cat" but not the start of "catalog".
Parentheses make a group. A group lets a quantifier apply to several characters, and it also captures what it matched, numbered from 1 by the opening bracket. In (\d+)-(\d+)-(\d+) the three groups hold the parts of a date, and a replacement can reuse them as $3/$2/$1. Named groups, written (?<year>\d{4}), are reused as $<year>. Use (?:...) when you need grouping without capturing.
The pipe | means "or": 0[1-9]|1[0-2] matches a month from 01 to 12. Alternation has the lowest precedence, so wrap it in a group when it sits inside a longer pattern.
Flags and what this site's tester offers
Flags follow the closing slash and change how the whole pattern behaves. g finds every match instead of stopping at the first. i ignores case. m lets ^ and $ match at each line. s lets . match line breaks. u turns on full Unicode handling.
The regex tester on this site has toggles for exactly those five (g, i, m, s, u), lists each match with its capture groups (named ones included), and has a replace box that accepts $1, $2 and $<name>. It runs your browser's own JavaScript engine, so what works there works in your JavaScript code. Other languages differ in small ways: Python spells named groups (?P<name>...), and some engines support features JavaScript lacks.
Greedy versus lazy
Quantifiers are greedy by default: they take as much as they can, then give characters back if the rest of the pattern fails. Against "<b>bold</b> text", the pattern <.+> matches the whole <b>bold</b> as one match, because .+ runs to the last >.
Adding ? after a quantifier makes it lazy, taking as little as possible. <.+?> with the g flag returns two matches, <b> and </b>. A negated class such as <[^>]+> gets the same result and is usually clearer and faster.
Lookahead in one minute
A lookahead checks what comes next without including it in the match. \d+(?=%) against "50% of 20 and 75%" returns "50" and "75" but not "20", and the percent signs are not part of the matches. (?!...) is the negative form. JavaScript also supports lookbehind, (?<=...) and (?<!...); for example (?<!\d)\d{6}(?!\d) finds a six-digit PIN code and skips the first six digits of a longer number. Older Safari versions did not support lookbehind, so check before using it in code that must run everywhere.
Six worked examples
- Loose email finder:
[\w.+-]+@[\w-]+\.[\w.-]+withg. On "Mail asha.k+news@example.co.in or bob@test.org, not @nobody or x@y" it returnsasha.k+news@example.co.inandbob@test.org. It is deliberately loose; real address validation is more complicated, and the reliable check is sending a message. - ISO date:
(\d{4})-(0[1-9]|1[0-2])-(0[1-9]|[12]\d|3[01])finds2026-10-11in "Due 2026-10-11 and 2026-13-40" and rejects the second date, whose month is 13. It does not know that 31 April does not exist. - Reorder a date: replace
(\d+)-(\d+)-(\d+)with$3/$2/$1and2026-10-11becomes11/10/2026. - Indian PAN-style identifier:
\b[A-Z]{5}\d{4}[A-Z]\b(five capitals, four digits, one capital). On "PAN ABCDE1234F and abcde1234f and ABCDE12345" onlyABCDE1234Fmatches. This checks the shape only, not that the PAN exists. - Extract numbers:
-?\d+(?:\.\d+)?withgon "Paid 1250.50 for 3 items, change -4.5" returns1250.50,3and-4.5. - Trim and collapse whitespace: replacing
^\s+|\s+$with nothing turns " hello world " into "hello world", and replacing\s+with a single space then gives "hello world".
When a pattern becomes slow
Most JavaScript engines match by backtracking: when a path fails they step back and try another. Nested quantifiers over the same characters, like ^(a+)+$, give the engine exponentially many ways to split the input. In a quick test, matching that pattern against 26 letter "a"s followed by a "b" took about two seconds, and every extra letter roughly doubles it.
This is called catastrophic backtracking, and on a server it can be used to freeze a request. Avoid nesting + or * inside another repeat, prefer specific classes over .*, and limit the length of untrusted input before matching it. Also remember that a regex cannot parse nested structures like HTML or JSON; use a real parser for those.
Frequently asked questions
Why does my pattern match more text than I expected?
Usually a greedy quantifier. `.*` and `.+` take as much as possible. Make it lazy with `.*?`, or use a negated class like `[^"]*` that cannot run past the character you want to stop at.
Why does it only find the first match?
Without the `g` flag JavaScript stops after one match. Turn on the global flag to get all of them.
Can I use regex to validate an email address?
Only loosely. A simple pattern can catch typing mistakes such as a missing @, but the full address grammar is too complex for a reasonable regex, and valid-looking addresses can still not exist. Send a confirmation email if it matters.
Do I need to escape the forward slash?
In a regex literal like /a\/b/ yes, because the slash ends the literal. In a text field of a tester, or in new RegExp("a/b"), no.