Skip to main content
Back to Blog

Mastering Regular Expressions: A Developer's Guide

A practical crash course on reading and writing regex: anchors, quantifiers, groups, and how to test patterns without guesswork.

Kashyap Thakar
8 min
RegexDevelopmentGuide
Mastering Regular Expressions: A Developer's Guide

Regular Expressions (Regex) are often seen as a dark art in programming. A string of characters like ^([a-z0-9_\.-]+)@([\da-z\.-]+)\.([a-z\.]{2,6})$ can look intimidating, but it is built from a small set of parts that this guide walks through.

What is Regex?

A regular expression is a sequence of characters that specifies a search pattern. It is used for searching, replacing and sanity-checking strings.

Common Patterns Explained

  • . (Dot): Matches any single character except line terminators (\n, \r, U+2028, U+2029) unless the s flag is set.
  • * (Asterisk): Matches 0 or more of the preceding element.
  • + (Plus): Matches 1 or more of the preceding element.
  • ? (Question Mark): Matches 0 or 1 of the preceding element.
  • \d: Matches any digit (0-9).
  • \w: Matches any word character (alphanumeric + underscore).

Practical Examples

1. Email Validation

^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$

This pattern checks the rough shape of an address: username, @, domain, dot, and an extension of two or more letters. It is a sanity check, not a validator. Real addresses can be rejected or accepted wrongly, and the only reliable test is sending a confirmation email.

2. Date Format (YYYY-MM-DD)

^\d{4}-\d{2}-\d{2}$

This checks the shape only: 2025-99-99 passes. Parse the date (or compare ranges) after the pattern matches.

Advanced Patterns

Character Classes

Character classes allow you to match any one of several characters:

[aeiou] // Matches any vowel
[0-9] // Matches any digit
[a-zA-Z] // Matches any letter
[^0-9] // Matches anything except digits (^ negates)

Anchors

Anchors don't match characters. They match positions:

^hello // Matches "hello" at the start of the string (of each line with the m flag)
world$ // Matches "world" at the end of the string (of each line with the m flag)
^hello world$ // Matches the entire string exactly

Groups and Capturing

Parentheses create groups that can be captured and reused:

(abc)+ // Matches "abc" one or more times
(hello|world) // Matches either "hello" OR "world"
(\d3)-(\d3)-(\d4) // Captures phone number parts

Common Regex Patterns

Phone Number (US Format)


^(\+?1[-.\s]?)?\(?([0-9]{3})\)?[-.\s]?([0-9]{3})[-.\s]?([0-9]{4})$
                    
                    

This pattern accepts common US formats: (123) 456-7890, 123-456-7890, 123.456.7890 and +1 123 456 7890. It checks the format only, not whether the area code exists.

Credit Card Number (Basic)


^\d{4}[-.\s]?\d{4}[-.\s]?\d{4}[-.\s]?\d{4}$
                    
                    

Matches 16-digit card numbers with optional separators. It does not match 15-digit American Express numbers, and it checks format only. The Luhn checksum is the usual next step.

URL Validation


^https?:\/\/(www\.)?[-a-zA-Z0-9@:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()@:%_\+.~#?&//=]*)$
                    
                    

Matches HTTP and HTTPS URLs with a dotted host name and an optional path or query string. Because the host must contain a dot, https://localhost:3000 is rejected. For real validation, new URL(input) is more reliable than any regex.

Performance Tips

  • Be specific: a pattern that says exactly what it wants (\d+, [^<]*) leaves the engine less to retry than one built on .*.
  • Avoid nested quantifiers: patterns like (a+)+ can take exponential time on some inputs (explained below).
  • Anchor when you mean the whole string: ^pattern$ states your intent, and a failed anchored match gives up quickly instead of trying every start position.
  • Measure rather than guess: micro-optimisations such as swapping a class for an alternation rarely matter next to the backtracking issues below.

How the Engine Actually Matches

JavaScript's regex engine is a backtracking matcher. It tries to match at the first position of the string, walks through your pattern left to right, and when a step fails it backs up to the most recent choice it made and tries the next option. If every option fails at that position, it moves one character forward and starts again. Two consequences follow. The match you get is the leftmost one, not the longest one, and alternation is ordered: the first branch that lets the whole pattern succeed wins.

"category".match(/cat|category/)[0]   // "cat"
"category".match(/category|cat/)[0]   // "category"

Put the longer, more specific alternative first, or anchor the pattern so a short branch cannot succeed early. Our Regex Tester is a quick way to see which branch wins on your own input. For syntax you can look up rather than reason about, keep the Regex Cheat Sheet open alongside this guide.

Greedy vs Lazy, and Why Specific Beats Both

A greedy quantifier (*, +, ?) grabs as much as it can and then gives characters back one at a time until the rest of the pattern fits. A lazy quantifier (add a trailing ?) does the opposite: it takes as little as possible and expands only when the rest of the pattern fails. Against <b>bold</b> and <b>more</b>:

/<b>.*<\/b>/    // "<b>bold</b> and <b>more</b>"  (greedy: runs to the LAST </b>)
/<b>.*?<\/b>/   // "<b>bold</b>"                  (lazy: stops at the first </b>)
/<b>[^<]*<\/b>/ // "<b>bold</b>"                  (negated class: no backtracking needed)

The negated class is usually the best choice. It states what you actually mean ("anything that is not the start of the next tag"), and the engine never has to retreat. Lazy quantifiers still backtrack: each time the rest of the pattern fails, the engine expands the lazy match by one character and retries.

Catastrophic Backtracking, Step by Step

In ^(a+)+$ the inner and outer + can split a run of a's in many different ways. When the input is a run of a's followed by a character that makes the match fail, such as aaaa...ab, the engine tries every possible split before giving up. The number of splits roughly doubles with each extra a, so a modest-looking string can freeze a page or a server thread. In a quick test on Node 24, /^(a+)+$/.test("a".repeat(30) + "b") took about eight seconds, and each extra a roughly doubles that. This is the root of ReDoS (regular expression denial of service) bugs.

The reliable fix is to remove the ambiguity. ^a+$ matches exactly the same strings and fails fast. When you cannot restructure the pattern, note that JavaScript regexes have no atomic groups or possessive quantifiers ((?>a+) and a++ are syntax errors in Node 24). A lookahead with a backreference gives the same effect, because a lookahead commits to its first match and never gives it back:

/^(?=(a+))\1$/.test("aaa")                        // true
/^(?=(a+))\1$/.test("a".repeat(100000) + "b")     // false, returns immediately

Lookaheads and Lookbehinds

Lookarounds assert that something is (or is not) next to the current position without consuming it, so they are zero-width like anchors. (?=...) and (?!...) look ahead, while (?<=...) and (?<!...) look behind (lookbehind arrived in ES2018 and is available in current browsers and Node).

"price: $42, cost: €17".match(/(?<=\$)\d+/)[0]   // "42"
"foobar foobaz".match(/foo(?!bar)\w+/)[0]         // "foobaz"

// Several independent conditions at one position (a password-shape check)
const pw = /^(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,}$/;
["Passw0rdOK", "password", "Sh0rt"].map(s => pw.test(s))   // [true, false, false]

// Thousands separators
"1234567".replace(/\B(?=(\d{3})+(?!\d))/g, ",")   // "1,234,567"

The last example reads as: at any position that is not a word boundary and is followed by one or more groups of three digits and then a non-digit, insert a comma. It works for plain integers. For display formatting in real code, Intl.NumberFormat handles locales and decimals for you.

Anchors, Multiline, and Other Flags

Without the m flag, ^ and $ match only at the very start and end of the whole string. In JavaScript, $ does not match before a trailing newline (some other engines, including Python's, do), so /^a$/.test("a\n") is false. With m, they match at every line boundary:

/^a$/.test("x\na\ny")     // false
/^a$/m.test("x\na\ny")    // true
"line1\nline2".match(/^\w+$/gm)   // ["line1", "line2"]
FlagEffect
gFind all matches. Makes the regex stateful (see below)
iCase-insensitive matching
m^ and $ match at each line boundary
s. also matches newline (/a.b/s.test("a\nb") is true)
uTreat the pattern and input as Unicode code points, and enable \p{L} property escapes
ySticky: match only at lastIndex
dInclude start and end indices for each group in the result

There is also a newer v flag, an upgraded form of u with stricter syntax that adds set operations inside character classes, such as [\p{L}--[a-z]] for "any letter except a to z".

JavaScript-Specific Gotchas

The g flag makes test() stateful

A regex with g (or y) remembers where its last match ended in lastIndex. Reusing one in test() or exec() gives alternating results:

const re = /a/g;
re.test("aa")   // true   (lastIndex is now 1)
re.test("aa")   // true   (lastIndex is now 2)
re.test("aa")   // false  (lastIndex resets to 0)

Drop the g for simple yes/no checks, or create the regex inside the function that uses it.

\w, \d and \b are ASCII-only

\w means [A-Za-z0-9_] and \d means [0-9], even with the u flag. (The one exception: with both u and i, \w also matches U+017F and U+212A.) /^\w+$/.test("naïve") is false, while /^\p{L}+$/u.test("naïve") is true. \b is defined in terms of \w, so /\bcafé\b/.test("café au lait") is false: the boundary after é is not recognized.

Emoji and the u flag

Without u, JavaScript matches UTF-16 code units, so "😀".length is 2 and /^.$/.test("😀") is false. With u it is true. Add the flag whenever user text may include emoji or characters outside the Basic Multilingual Plane.

Named groups and matchAll

const date = /(?<y>\d{4})-(?<m>\d{2})-(?<d>\d{2})/;
"2025-04-28".match(date).groups.y                  // "2025"
"2025-04-28".replace(date, "$<d>/$<m>/$<y>")       // "28/04/2025"

[..."a1b22c333".matchAll(/[a-z](\d+)/g)].map(m => [m[0], m[1], m.index])
// [["a1", "1", 0], ["b22", "22", 2], ["c333", "333", 5]]

Prefer named groups over numbered ones in anything longer than a one-liner. They survive refactors that add or remove groups. matchAll requires the g flag and returns an iterator of full match objects, which is easier than looping over exec().

Debugging a Pattern That Won't Match

  • Shrink it: remove everything after the first part and confirm that part matches, then add pieces back one at a time.
  • Check the string, not just the pattern: invisible characters such as non-breaking spaces, trailing newlines and Windows line endings are common culprits. Log JSON.stringify(input) to see them.
  • Check escaping layers: in a string passed to new RegExp() you need "\\d+", because the string literal consumes one backslash. A regex literal needs only /\d+/.
  • Check flags and anchors: a missing m, s or u explains many "works in the tester, not in my code" reports. Make sure the tester uses the same flavor and flags as your runtime.
  • Test near-misses: feed it strings that should fail, including long ones, to catch over-matching and slow backtracking.

Testing Your Patterns

Writing a regex is trial and error, and one small mistake makes a pattern match too much or too little. Test against real samples, including strings that should fail. Our Regex Tester takes a pattern and a test string, highlights the matches as you type, and lists each match with its captured groups. You can toggle the g, i, m, u, y and s flags, and it reports how long the match took.

It runs on your browser's own JavaScript engine, so what you see is what new RegExp() will do in the browser. It does not explain the pattern or test several strings at once, and it does not support the d or v flags, so for those use the console. Patterns written for PCRE, Python or RE2 can behave differently.

Common Mistakes to Avoid

  • Forgetting to escape special characters: Characters like ., *, +, and ? have special meanings. Use \. to match a literal period.
  • Over-matching: .* is greedy, so it can swallow more than you intended (see the greedy versus lazy section above).
  • Not anchoring patterns: Without ^ and $, your pattern might match part of a string when you want to match the whole thing.
  • Assuming regex can do everything: Some tasks (like parsing HTML or validating email addresses) are better handled by dedicated parsers or libraries.

Frequently Asked Questions

What is the difference between greedy and lazy quantifiers?

A greedy quantifier matches as much as possible and backs off only if the rest of the pattern fails. A lazy one (with a trailing ?) matches as little as possible and expands only when needed. Often a negated character class such as [^<]* is clearer and faster than either.

Why does my regex work in a tester but not in my code?

The usual causes are different flags, a different regex flavor, or escaping. Inside a string passed to new RegExp() every backslash must be doubled. Also check that the input does not contain invisible characters such as trailing newlines or non-breaking spaces.

What is catastrophic backtracking and how do I avoid it?

It happens when a pattern with nested or overlapping quantifiers, like ^(a+)+$, fails on a long near-match and the engine tries an exponential number of ways to split the input. Remove the ambiguity, limit input length, and use a linear-time engine for untrusted input where you can.

Do I need the g flag?

Use g when you want every match from match(), matchAll() or replace(). Avoid it for test() on a reused regex object, because the saved lastIndex makes consecutive calls return inconsistent results.

Does JavaScript support lookbehind?

Yes. Lookbehind assertions such as (?<=\$)\d+ have been part of the language since ES2018 and work in current browsers and Node.js. Very old environments may lack support, so check your targets before relying on them.

Written by

Spotted a mistake? Let me know