Reading, testing and maintaining a regex

Intermediate · 13 min

Read an unfamiliar pattern in pieces, comment it where JavaScript has no verbose mode, and pin its behaviour with a should-match table run as a test.

Before thisInline flags and verbose modeNamed capture groupsWriting patterns that run fastValidating input: emails, URLs and addressesWhen not to use a regex

RobertElderSoftware · 13 min

Reading, testing and maintaining a regex

The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.

Taught by RobertElderSoftwareReport a problem with this video
Not started
Set this lesson's status

What you'll learn

  • Read a pattern left to right in pieces, say each piece in words, then test your reading with inputs that sit on its edges. I found the HTML email pattern allows a 63-character domain label, rejects 64, and puts no cap on total length.
  • JavaScript has no verbose flag: new RegExp('a', 'x') throws. Build the pattern from named String.raw parts with a comment on each. Python's re.X, PCRE's (?x) and Perl's /x do allow comments.
  • Keep a table of strings that should match and strings that should not, and run it as a unit test. My 18-case IPv4 table passed 19 of 19 checks, then caught an innocent-looking edit that allowed leading zeros.
  • Put the cases that came from real bugs in the table. The table is the documentation of what the pattern is for.
  • Practice builds fluency. Regex crosswords, katas and regex golf teach you to read patterns faster, but production patterns are judged on clarity and tests, not length.

Code you read more than you write

Months after you write a regex, someone opens the file and finds a line like this one. It is the pattern the HTML standard uses for email addresses:

/^[a-zA-Z0-9.!#$%&'*+\/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/

That someone might be you. The skills that matter are reading it, proving you read it correctly, and leaving it in a state the next reader can trust.

Reading: pieces, then experiments

Do not read left to right character by character. Split at the structure. Here there are three pieces:

  1. ^[a-zA-Z0-9.!#$%&'*+\/=?^_{|}~-]+is the part before the@`: one or more characters from a class that includes letters, digits and a list of symbols.
  2. @[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])? is the first domain label: an alphanumeric, then optionally up to 61 alphanumerics or hyphens followed by an alphanumeric.
  3. (?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$ is zero or more further labels, each after a dot.

Now check the reading with inputs at the edges. In Node 26:

label of 63 characters:     matches
label of 64 characters:     rejected
one-character label (a@b.c)  matches
"x@ab-.com" (ends in dash)   rejected
"x@a-b.com"                  matches
"a+b=c@x.io"                 matches
"a(b)@x.io"                  rejected
"x@a.com." (trailing dot)    rejected

The 63 limit comes from one first character, up to 61 in the middle and one last: 1 + 61 + 1. That matches my reading. I also found something the pattern does not say: I fed it a domain of five labels, about 300 characters in total, and it matched. There is no cap on the whole address. If a limit exists elsewhere in the standard, this pattern does not enforce it, and I did not check what that limit is. Finding gaps like this is the point of experimenting rather than just reading.

The video for this lesson suggests the same approach for debugging: start from the smallest piece that works and grow it.

JavaScript has no verbose mode

Python, PCRE and Perl let you spread a pattern over lines with comments. I ran the IPv4 pattern three ways with comments:

Python    re.X                  192.168.1.1 True   256.1.1.1 False
pcre2grep (?x)  ... # comment   192.168.1.1 matched, 256.1.1.1 did not
Perl      /x                    192.168.1.1 match  256.1.1.1 no

JavaScript has no such flag: new RegExp("a", "x") threw Invalid flags supplied to RegExp constructor 'x'. The workaround is to build the pattern from named pieces:

const OCTET = String.raw`(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)`; // 0-255, no leading zeros
const DOT = String.raw`\.`;
export const IPV4 = new RegExp(`^${OCTET}(?:${DOT}${OCTET}){3}$`);

String.raw keeps backslashes as typed, so you do not double them. Each piece gets a name and a comment, and the combined pattern reads like a sentence. I checked that the composed pattern’s .source was identical to the hand-written one-liner, so nothing changed in assembly. A word of caution from Python: under re.X, unescaped whitespace is ignored, so a space you want must be escaped or put in a class. I confirmed that a\ b and [ ]b still match a space under re.X.

Testing: a table, run as a test

A should-match table is the most useful comment you can write. This is a real file, run with Node’s built-in test runner (node --test):

const shouldMatch = ["0.0.0.0", "1.2.3.4", "255.255.255.255", "199.99.9.100", ...];
const shouldNotMatch = ["256.1.1.1", "1.2.3", "01.2.3.4", "1.2.3.4\n", " 1.2.3.4", "1..3.4", "", ...];
for (const s of shouldMatch) test(`matches ${JSON.stringify(s)}`, () => assert.ok(IPV4.test(s)));
for (const s of shouldNotMatch) test(`rejects ${JSON.stringify(s)}`, () => assert.ok(!IPV4.test(s)));

Eighteen cases plus a check that the composed and one-line sources agree gave pass 19, fail 0. Then I made an edit that looks like a harmless simplification, replacing [1-9]?\d with \d{1,2}:

✖ rejects "01.2.3.4"
✖ rejects "1.2.3.04"
✖ composed pattern equals the one-liner
ℹ pass 16
ℹ fail 3

\d{1,2} allows 01, which the original deliberately rejected. A reviewer reading the diff might miss that. The table did not. When a bug is reported, add the input first and watch it fail, then fix the pattern. The table then becomes the record of every mistake the pattern has made. Python’s unittest or pytest with parameters works the same way.

Keeping it maintainable

  • Name constants for repeated pieces, as above, rather than pasting the same octet three times.
  • Put a one-line comment above each pattern saying what it accepts and what it deliberately rejects.
  • Record the flags, because the same source with g or i behaves differently.
  • Link to the specification or source of a borrowed pattern and note any changes.
  • For user-supplied text, escape it first, as building patterns from input covers.
  • If the pattern is too long to explain, split the problem or reach for a parser.

Practice builds fluency

Reading patterns quickly comes from seeing many of them. Regex crosswords and “golf” puzzles, where you find the shortest pattern that separates two lists, are good for that. I confirmed the Regex Crossword, RegexOne and Regex Golf sites load, but I did not work through them, so I cannot rate them. A caution: golf rewards short, and your production code should reward clear. Use golf to train your eye, not to set your style.

About the video

“3 Top Secret Regex Debugging Techniques Experts Use” by RobertElderSoftware was published 13 November 2020 and runs 13 minutes 3 seconds. The description lists three techniques: separate your escaping problems (print the pattern before compiling it), use the [...] method (single characters in a class need less escaping), and debug from the ground up by starting with a one-character regex and building toward the full one. The chapters follow that order. I couldn’t read a transcript, so I can’t say which flavours it demonstrates. It is about debugging, not about verbose mode, test tables or maintenance, which are from my own runs here. English per its title and description.

What I did not run

regex101’s explanation panel and debugger, regex-linting tools, the practice sites above, and Python’s unittest or pytest versions of the table. I did not measure how a table scales to hundreds of cases.

Where to go next

That is the end of this roadmap. For the shell side of the same patterns, see searching with grep and editing streams with sed. For regex as part of the JavaScript language, see regular expressions.

Check yourself

  1. 01How do you read a pattern you did not write?

    Split it into pieces at groups and alternations, say each piece in words, and write down what it accepts. Then test your reading with inputs at the edges of each piece, such as the longest and shortest allowed, and one just past it.

  2. 02JavaScript regex has no x flag. What do you do to comment a long pattern?

    Assemble it from named String.raw constants, one per piece, each with a comment, and join them in new RegExp(...). Give the whole pattern a name. Keep one-liner and composed forms identical by testing that their .source strings are equal.

  3. 03Why is a table of should-match and should-not-match strings valuable?

    It records what the pattern is meant to do, and it fails when an edit changes behaviour. In my test, replacing [1-9]?\d with \d{1,2} looked like a simplification and broke three checks, because it allowed leading zeros.

  4. 04A bug is reported: the pattern accepts a bad input. What is the first step?

    Add that input to the should-not-match table and watch it fail. Then fix the pattern until the whole table passes. The fix is now protected against regression.

Go deeper

Notes

Private to you

Esc
↑↓ navigate↵ open? shortcuts

Keyboard shortcuts

Press Esc to close

Anywhere

⌘K
Search and commands
/
Search
?
This sheet
Esc
Close

Reading a lesson

J
Next lesson
K
Previous lesson
B
Bookmark