Regular expressions are one of the most useful tools in programming and one of the easiest to get subtly wrong. A validation pattern accepts input it should reject. A log parser silently skips lines with an unexpected space. A search-and-replace across a codebase changes more than you intended. Most of these bugs come from writing a pattern in one go and testing it against a single example.
This guide shows a reliable way to build and debug regular expressions: grow them in small steps against realistic text, understand exactly what each flag and group does, and check replacements before they touch real data. The examples use JavaScript regex syntax, which is also what our tester uses.
How a regex engine reads your pattern
A regular expression is a small program that the engine runs against your text, character by character. Most modern engines, including JavaScript's, work by backtracking: they try to match from each starting position, and when part of the pattern fails, they step back and try the next alternative. Three consequences follow:
- The engine returns the first match it finds from the left, not the longest or the "best".
- Quantifiers like
*and+are greedy: they take as much as they can, then give back characters only if the rest of the pattern needs them. - A badly structured pattern can make the engine try an enormous number of paths before giving up.
Keeping these in mind explains most surprising results.
Test a regex with our tool
The Regex Tester runs your pattern with the browser's own JavaScript engine, in a background worker so a runaway pattern cannot freeze the page.
- Open the Regex Tester. Type the pattern into Regular expression, without the surrounding slashes. Load sample fills in an email-matching example with named groups.
- Tick the flags you need: g (global), i (ignore case), m (multiline), s (dot-all), u (Unicode) and y (sticky).
- Paste realistic text into Test string. Matches are highlighted as you type, and a badge shows the number of matches.
- Check Match details: each match with its start and end index, and each capture group (numbered and named) with its value and position. Copy JSON or Download exports the list.
- Optionally enter a Replace with pattern such as
$1or$<name>and read the replaced text below it, then Copy result.
The Cheat sheet beside the tester inserts tokens into the pattern at the cursor when you click them. If a pattern is invalid, the error from the engine is shown instead of highlights. If it runs for more than 1.5 seconds, the test is stopped with a warning about catastrophic backtracking. Up to 1,000 matches are listed.
Build patterns in small steps
Say you need to pull invoice numbers like INV-2024-0017 out of text. Build up the pattern, checking the highlights at every step:
INVmatches the literal prefix. Confirm it highlights where expected.INV-\d{4}adds a hyphen and exactly four digits.INV-(\d{4})-(\d{4})captures year and sequence number separately.\bINV-(\d{4})-(\d{4})\badds word boundaries soXINV-2024-00171does not produce a partial match.
Then paste in text that should not match: lowercase prefixes, three-digit years, numbers inside longer codes. A pattern is only tested when you have tried to break it.
Flags, and what they really change
| Flag | Effect |
|---|---|
g |
Find all matches instead of stopping at the first |
i |
Case-insensitive matching |
m |
^ and $ match at the start and end of every line, not just the whole text |
s |
. also matches line breaks |
u |
Full Unicode mode: correct handling of emoji and \p{...} property classes |
y |
Sticky: match only at the current position |
The m flag is the one most often forgotten. ^\d+$ against a multi-line list matches nothing without it, because the whole text is not a single number.
Groups and replacements
Parentheses do two jobs: group part of a pattern, and capture what it matched.
(abc)captures, and is available as$1,$2and so on.(?<year>\d{4})is a named group, available as$<year>. Named groups make both patterns and replacements self-explanatory.(?:abc)groups without capturing, keeping the group numbers of the others stable.
For example, to turn 2024-03-31 into 31/03/2024:
"2024-03-31".replace(/(?<y>\d{4})-(?<m>\d{2})-(?<d>\d{2})/, "$<d>/$<m>/$<y>");
// "31/03/2024"
In the replacement, $& inserts the whole match and $$ a literal dollar sign. Without the g flag, only the first match is replaced, which the tester points out under the replacement box.
Greedy vs lazy quantifiers
Greedy quantifiers are the classic cause of "matched too much":
"<b>a</b><b>c</b>".match(/<b>.*<\/b>/)[0]; // "<b>a</b><b>c</b>"
"<b>a</b><b>c</b>".match(/<b>.*?<\/b>/)[0]; // "<b>a</b>"
.* runs to the end of the text and backs off only as far as the last </b>. Adding ? makes it lazy, taking as little as possible. Often an even better fix is a negated class: <b>[^<]*<\/b> cannot cross a tag at all. (For real HTML, use a parser; regex is fine for quick searches, not for reliable HTML processing.)
Catastrophic backtracking
Some patterns take exponentially longer as the input grows, especially when they fail to match. The typical shape is a nested quantifier over something that can match in several ways: (a+)+$, (\w+\s?)*$, or (.*,)*. On a long string that almost matches, the engine tries every way of dividing the text between the inner and outer loops.
This is not just slow; it is a known denial-of-service risk (ReDoS) when user input reaches such a pattern on a server. To avoid it:
- avoid nested quantifiers where the inner and outer parts can match the same characters;
- prefer specific classes (
[^,]*) to.*; - anchor patterns and keep alternatives mutually exclusive.
If the tester stops your pattern with a timeout, rewrite it rather than raising the timeout in production.
Regex flavours differ
JavaScript, Python, PCRE (PHP), Java, .NET and POSIX tools like grep and sed share most basic syntax but differ in details: lookbehind support, named group syntax ((?P<name>...) in Python), possessive quantifiers, and whether \d matches non-ASCII digits. A pattern tested here is reliable for JavaScript and usually close for others; test it in the target language before relying on it. When a regex must live inside a string literal in code, escape its backslashes with the String Escape tool.
Frequently asked questions
Why does my regex work in the tester but not in my code?
Common causes are missing backslash escapes in a string literal (writing "\d" where "\\d" is needed, for example with new RegExp()), a different regex flavour, or a missing flag. In JavaScript, also watch for reusing a g regex with test(), which remembers its lastIndex between calls and alternates between true and false.
What does the g flag do?
It makes the engine find every match instead of stopping at the first. It also makes replace operations change all matches.
How do I match a literal dot or bracket?
Escape it with a backslash: \., \(, \[. Inside a character class, most characters are literal, so [.] also matches a dot.
Can I extract emails or URLs without writing a regex?
Yes. The Extract Emails and Extract URLs tools pull them out of text directly, and Find and Replace handles simple substitutions.
Is my test text uploaded?
No. Patterns and text are processed by your browser only.