A regular expression, or regex, is a small pattern that describes text. With one line you can find every email address in a document, check that a postcode field contains the right characters, or reformat thousands of dates. Regex is built into almost every programming language, code editor, spreadsheet tool and database.
It also has a reputation for being unreadable. That reputation is partly deserved — but the core of regex is a small set of building blocks, and once you know them most patterns become readable. This guide uses JavaScript syntax, which is also what our regex tester uses. Most of it works the same way in Python, PHP, Java, Go and other languages, though advanced features vary.
Your first pattern
The simplest regex is plain text. The pattern cat matches the letters c, a, t in that order — in “cat”, “concatenate” and “scatter”.
In JavaScript you write a regex between slashes, with optional flags after the closing slash:
const re = /cat/gi;
"Cat and caterpillar".match(re); // ["Cat", "cat"]
The g flag finds every match instead of just the first; i ignores case. In the regex tester you type the pattern without slashes and tick the flags.
Special characters
Some characters have special meanings. To match them literally, put a backslash in front: \. matches a full stop, \? a question mark.
The characters that need escaping in most contexts are:
. * + ? ^ $ { } ( ) [ ] | \ /
The / only needs escaping when you write a regex literal between slashes.
Character classes
Square brackets match one character from a set.
[aeiou]matches any one vowel.[0-9]matches any digit;[a-z]any lowercase ASCII letter.[A-Za-z0-9_]matches a letter, digit or underscore.[^0-9]— a caret at the start negates the set: any character that is not a digit.
There are shorthands for common sets:
| Token | Matches |
|---|---|
\d | A digit 0–9 |
\w | A “word” character: letter, digit or underscore (ASCII only by default) |
\s | Whitespace: space, tab, newline and similar |
\D, \W, \S | The opposite of each of the above |
. | Any character except a line break (unless the s flag is set) |
Note that \w and \d only cover ASCII letters and digits in JavaScript by default. To match letters in any language, use Unicode property escapes with the u flag, such as \p{L} for any letter.
Quantifiers: how many
Quantifiers say how many times the previous item may repeat.
| Quantifier | Meaning |
|---|---|
* | Zero or more |
+ | One or more |
? | Zero or one (optional) |
{3} | Exactly 3 |
{2,} | 2 or more |
{2,5} | Between 2 and 5 |
Examples:
\d+matches one or more digits: “7”, “42”, “2026”.colou?rmatches “color” and “colour”.\d{4}-\d{2}-\d{2}matches a date shaped like 2026-11-28 (it doesn’t check the date is real).
Greedy and lazy
By default quantifiers are greedy: they match as much as possible. Given the text <b>one</b> and <b>two</b>, the pattern <b>.*</b> matches the whole string from the first <b> to the last </b>.
Adding ? after a quantifier makes it lazy: it matches as little as possible. <b>.*?</b> matches <b>one</b> and then <b>two</b> separately.
(Parsing HTML with regex is fragile in general; for real HTML, use a proper parser. It makes a good illustration of greedy matching, though.)
Anchors and boundaries
Anchors match a position, not a character.
^matches the start of the string (or of each line with themflag).$matches the end of the string (or of each line withm).\bmatches a word boundary: the point between a word character and a non-word character.
So ^\d+$ matches a string that is entirely digits, and \bcat\b matches “cat” as a whole word but not inside “concatenate”.
Anchors are essential for validation. Without them, \d{5} would accept “abc12345xyz” because it contains five digits somewhere.
Groups and alternation
Parentheses group parts of a pattern and capture what they match.
const m = "2026-11-28".match(/(\d{4})-(\d{2})-(\d{2})/);
m[1]; // "2026" m[2]; // "11" m[3]; // "28"
(?:...)groups without capturing, which is useful when you only need grouping for a quantifier or alternation.(?<year>\d{4})creates a named group, available asm.groups.year.|means “or”:cat|dogmatches either word. Combine with a group to limit its scope:(cat|dog)s?.
Back-references
Inside a pattern, \1 refers to whatever the first group matched. \b(\w+)\s+\1\b finds repeated words such as “the the”.
Replacements
In replacements, $1, $2 and $<name> insert captured groups. To turn 2026-11-28 into 28/11/2026:
"2026-11-28".replace(/(\d{4})-(\d{2})-(\d{2})/, "$3/$2/$1");
The regex tester previews replacements as you type.
Flags
| Flag | Effect |
|---|---|
g | Global: find all matches, not just the first |
i | Ignore case |
m | Multiline: ^ and $ match at line breaks |
s | Dotall: . also matches line breaks |
u | Unicode: correct handling of characters outside the basic plane and \p{...} escapes |
y | Sticky: match only at the current position |
Lookarounds
Lookarounds check what comes before or after a position without including it in the match.
(?=...)positive lookahead:\d+(?= kg)matches the number in “25 kg” but not the unit.(?!...)negative lookahead:\b\w+\b(?!\.)matches words not followed by a full stop.(?<=...)positive lookbehind:(?<=\$)\d+matches digits after a dollar sign.(?<!...)negative lookbehind.
Lookbehind is supported in modern JavaScript engines but not in every regex flavour, so check before using it elsewhere.
Common patterns, with honest caveats
These are practical starting points, not perfect validators. Test them on your own data.
| Purpose | Pattern | Caveat |
|---|---|---|
| Trim spaces | ^\s+ and \s+$ | Use your language’s trim function when available |
| Simple email check | ^[^\s@]+@[^\s@]+\.[^\s@]+$ | Catches typos only; send a confirmation email to truly verify |
| Digits only | ^\d+$ | ASCII digits only |
| ISO date shape | ^\d{4}-\d{2}-\d{2}$ | Doesn’t reject 2026-13-45; parse to validate |
| Hex colour | ^#(?:[0-9a-fA-F]{3}){1,2}$ | Ignores 4- and 8-digit alpha forms |
| Repeated word | \b(\w+)\s+\1\b | Add the i flag to catch “The the” |
| Collapse spaces | \s{2,} replaced with a single space | Also collapses line breaks |
A note on email addresses: the full rules for valid addresses are complicated, and many “complete” email regexes either reject real addresses or accept invalid ones. A simple shape check plus a confirmation email is more reliable and kinder to users.
For phone numbers, postcodes and similar data, formats differ between countries. Rather than forcing one pattern, accept a reasonable range of characters and normalise them, or use a well-maintained library for that data type.
Performance and catastrophic backtracking
Most regexes run in microseconds. A few run for seconds, minutes or longer, because of catastrophic backtracking: the engine tries an enormous number of ways to match before giving up.
The classic warning sign is a nested quantifier over overlapping options, such as (a+)+$ or (\w+\s?)*$, applied to a long string that almost matches. Each extra character can double the work.
To avoid it:
- Avoid nesting quantifiers over the same characters.
- Make alternatives mutually exclusive where possible.
- Anchor patterns, and be as specific as you can (
[^"]instead of.inside quotes). - Limit input length before running a regex on untrusted text.
- Test with long, nearly matching input.
On servers, a slow regex applied to user input can be exploited to tie up CPU — a type of denial-of-service. Our regex tester runs patterns in a background worker and stops any that take longer than 1.5 seconds, so you can spot the problem safely.
A workflow for writing regexes
- Collect real examples of text that should and shouldn’t match. Paste them into the tester.
- Start small: match one simple part, then extend.
- Add anchors if you are validating a whole value.
- Use groups for the parts you need to extract.
- Comment your pattern in code, or build it from named pieces, so others can maintain it.
- Write tests for the examples you collected.
Regex is often one tool among several when cleaning data. Our duplicate line remover handles deduplication and sorting without any pattern writing, and the text diff checker shows exactly what a find-and-replace changed.
Where to go next
Once you are comfortable with the basics, the next steps are your language’s regex documentation (for flags and features it supports), Unicode property escapes for international text, and using regex in your editor’s search to refactor code.
If your team is building forms, data imports or search features and needs validation done properly, KRA Digital’s web application development team can help. For definitions of related terms, see the web development glossary. Our guide to cron expressions covers another compact syntax developers meet often.
Frequently asked questions
What is a regular expression used for?
Finding, validating, extracting and replacing text that follows a pattern: for example finding all dates in a document, checking that a form field contains only digits, or renaming files in bulk. Regex is supported in most programming languages, editors and many spreadsheet and database tools.
Is regex the same in every language?
The core syntax — classes, quantifiers, anchors, groups — is broadly shared. Features such as lookbehind, named groups, Unicode properties and flags differ between engines, so check your language’s documentation for advanced features.
How do I match a full stop or other special character?
Escape it with a backslash: \. matches a literal full stop, \( a literal opening parenthesis. Inside square brackets most characters lose their special meaning, so [.] also matches a full stop.
Should I validate email addresses with regex?
Use a simple pattern to catch obvious typos, such as a missing @ or domain, then confirm the address by sending an email. Complex email regexes often reject valid addresses.
Why is my regex so slow?
Usually because of catastrophic backtracking caused by nested or overlapping quantifiers. Make the pattern more specific, avoid patterns like (a+)+, anchor it, and limit the length of input you test against.