Readable, Tested and Unicode-Aware Regex
Write patterns others can maintain using verbose mode and named parts, test them with match and non-match cases, and handle international text with Unicode.
Welcome back!
Step 1 of 14Learn
Write-only code
Regex has a reputation as "write-only code": easy to write, impossible to read a month later. Here's a pattern from a real-looking codebase:
^(?:\+?1[-. ]?)?\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$It's a US phone number validator, but it takes a careful reading to see that. Unreadable patterns are dangerous: nobody dares to fix them, bugs hide in them, and people copy them without understanding.
Three techniques make patterns maintainable:
- Verbose mode. Python's
re.VERBOSE(inline flag(?x), also in PCRE, Java and others) ignores whitespace in the pattern and allows comments after#. You can lay a pattern out over several lines and explain each part. - Build from named pieces. In code, assemble long patterns from well-named variables:
const OCTET = "(?:25[0-5]|...)", then combine them. JavaScript has no verbose flag, so this is the main readability tool there. - Named groups instead of numbered ones, so both the pattern and the code that reads it say what each part means.
Also remember the simplest option: don't use regex when plain string methods are clearer. text.startsWith("http"), text.includes("@") and text.split(",") beat regex for simple cases.
Step 2 of 14Diagram
The phone pattern, piece by piece
Tap a shape with to see more.
- (?:\+?1[-. ]?)?
Optional country code: +1, 1-, 1. or nothing.
- \(?([0-9]{3})\)?
Area code, parentheses optional. Group 1.
- [-. ]?
Optional separator.
- ([0-9]{3})
Exchange. Group 2.
- [-. ]?([0-9]{4})$
Separator and line number. Group 3.
Step 3 of 14Practice · Choose one
In Python, what does the re.VERBOSE flag allow?
Step 4 of 14Learn
Verbose mode in practice
Here's the phone pattern rewritten in Python's verbose mode:
PHONE = re.compile(r"""
^
(?:\+?1[-.\s]?)? # optional country code: +1, 1-, 1.
\(?(?P<area>\d{3})\)? # area code, parentheses optional
[-.\s]? # optional separator
(?P<prefix>\d{3}) # exchange
[-.\s]? # optional separator
(?P<line>\d{4}) # line number
$
""", re.VERBOSE)Each piece is on its own line with a comment explaining its job, and named groups replace anonymous numbers. A reviewer can now check each rule separately, and changing one part doesn't require re-reading the entire pattern.
Two details matter in verbose mode. Literal spaces are ignored, so use \s, [ ] or an escaped space when you need to match one. And a literal # must be escaped as \# or put in a class, [#], or it starts a comment.
In JavaScript, the equivalent is composing pieces:
const AREA = String.raw`\(?(\d{3})\)?`;
const SEP = "[-.\\s]?";
const PHONE = new RegExp("^" + AREA + SEP + String.raw`(\d{3})` + SEP + String.raw`(\d{4})$`);String.raw keeps backslashes as written, avoiding the double-escaping problem of normal strings.
Step 5 of 14Practice · True or false
In verbose mode, a space typed inside the pattern matches a literal space in the text.
Step 6 of 14Learn
Testing patterns properly
A regex is code, and it deserves tests. The most useful habit is writing two lists before or while you write the pattern:
- Should match: typical cases and edge cases. For a ZIP code: "90210," "00501" (leading zeros are real), "90210-1234."
- Should not match: near-misses. "9021," "902101," "90210-," "90210-12," "ABCDE," " 90210" with a leading space, and an empty string.
Near-misses are where bugs hide. A pattern without anchors passes "902101." A pattern with \d{4,5} passes "9021." Only explicit negative cases reveal this.
Put both lists into automated tests that run on every change:
const ok = ["90210", "00501", "90210-1234"];
const bad = ["9021", "902101", "90210-", "ABCDE", ""];
for (const s of ok) console.assert(ZIP.test(s), "should match: " + s);
for (const s of bad) console.assert(!ZIP.test(s), "should not match: " + s);Interactive tools help while developing. Online regex testers highlight matches as you type, explain each part of a pattern, show captured groups and let you choose the flavor. Some show a step count that warns about backtracking problems. Use them to explore, then copy your test strings into real tests so the knowledge isn't lost.
Step 7 of 14Compare
Test lists for a ZIP code pattern
| Aspect | Should match | Should not match |
|---|---|---|
| Typical | 90210 | ABCDE |
| Edge | 00501 (leading zeros) | 9021 (too short) |
| Extended form | 90210-1234 | 90210-12 |
| Sneaky | — | " 90210" (leading space), empty string |
Step 8 of 14Practice · Put in order
Put these steps for developing a reliable validation regex in a sensible order.
Drag the items, or use the arrow buttons, to put them in order.
- Check the pattern for nested quantifiers or other backtracking risks
- Build the simplest pattern for the core shape
- Turn the example lists into automated tests that run on every change
- Add anchors and the remaining details piece by piece, testing each change
- Write down examples that should match and near-misses that should not
Step 9 of 14Learn
Unicode: beyond A to Z
Real text isn't limited to English letters. Names, addresses and product reviews contain "é," "ß," "ç," Cyrillic, Greek, Arabic, Chinese and emoji. ASCII classes like [A-Za-z] silently fail on all of them, and \w and \b behave differently between languages and modes.
Modern engines support Unicode property escapes, which match characters by category:
| Escape | Matches |
|---|---|
\p{L} | any letter in any script |
\p{Lu} | uppercase letters |
\p{N} | any numeric character |
\p{P} | punctuation |
\p{Script=Greek} | Greek characters |
\P{L} | anything that is not a letter |
In JavaScript, property escapes require the u flag: /^\p{L}+$/u.test("Zoë") is true, while /^[A-Za-z]+$/.test("Zoë") is false. Python's built-in re module doesn't support \p{...}, but its \w already matches Unicode letters for text strings, and the third-party regex module adds full property support. PCRE, Java and .NET support property escapes too.
One more subtlety: some characters can be written in more than one way. "é" can be one code point or "e" plus a combining accent. Normalizing text first (for example with str.normalize("NFC") in JavaScript or unicodedata.normalize in Python) makes matching consistent.
Step 10 of 14Compare
ASCII classes vs. Unicode properties
| Aspect | [A-Za-z]+ | \p{L}+ (with u flag) |
|---|---|---|
| Ana | Match | Match |
| José | Fails at é | Match |
| Straße | Fails at ß | Match |
| Δήμητρα | No match | Match |
Step 11 of 14Practice · Code challenge
Write isName(text) that returns true if the text is one or more words made of letters from any language, where words are separated by single spaces, hyphens or apostrophes (for example "Zoë", "Seán O'Brien", "Anne-Marie Lee"). Digits, double spaces and leading or trailing separators are not allowed. Use Unicode property escapes with the u flag.
isName("Zoë")isName("Seán O'Brien")isName("Anne-Marie Lee")isName("Μαρία")isName("R2D2")isName("Ana Ruiz")isName("-Ana")
Step 12 of 14Practice · Match the pairs
Match each Unicode property escape to a character it matches.
Tap an answer, then tap the place where it belongs (or drag it there).
\p{L}\p{N}\p{P}\p{Lu}
Step 13 of 14Note
Step 14 of 14Practice · Choose one
A JavaScript pattern /^\p{L}+$/ (without flags) is used to validate names. What happens?
Lesson complete!