Why do regexes look like line noise?
Where this mini-language came from, why it's so terse, how to read it piece by piece, and when you don't need it.
/^[\w.-]+@[\w-]+\.[a-z]{2,}$/i and asked whether I'd just walked across the keyboard. Rude, but fair. Why do regexes look like noise?Because they're a separate language, about forty-five years older than JavaScript. In 1951 the mathematician Stephen Kleene described "regular sets" — a precise way to define patterns of strings. In 1968 Ken Thompson built them into a text editor, and later into ed, the Unix editor. The command g/re/p — "globally search for a regular expression and print" — was so handy it became a program of its own: grep. Then the Perl language turned regexes into a superpower, and from Perl the syntax spread to almost every language — JavaScript included.
Why so terse? Back then you talked to a computer through a teletype: every character was slowly typed onto paper. Patterns were written right inside a command, so each character is a whole command. It's like math notation: x² is shorter than "x multiplied by itself". The price of brevity is an unfamiliar look. But \d{3} is quicker to write than "three digits in a row", and it means the same.
The secret to reading one: you don't read it all at once — you take it apart left to right, like a sentence word by word. Take a US phone check, /^\+1\d{10}$/:
^— from the very start of the string;\+— a plus sign. The backslash is needed because a bare+is the "one or more" command;1— just the digit one;\d{10}— exactly ten digits;$— and the string ends right there.
const phone = /^\+1\d{10}$/;
console.log(phone.test("+15551234567"));
console.log(phone.test("5551234567"));
console.log(phone.test("+1 555 123 4567"));replace.To keep regexes from turning into noise, detectives follow three rules:
- name it:
const phone = /…/is half the documentation already; - keep it short: two simple checks beat one giant one;
- test on examples: a good string, a bad one and an edge case — like the code above.
const tag = "<b>Byte <b>and</b> Mittens</b>";
console.log(tag.match(/<b>.*?<\/b>/)[0]);Myth or fact?
Decide whether the statement is true. Got it wrong? Try again; once you're right, Byte explains what's going on.