Coding

Regex, Explained Without the Headache

Regex, Explained Without the Headache

Cover: Regex, Explained Without the Headache

Regex looks like line noise until you realize it's built from a small handful of symbols, each doing one simple job. Learn these six and you can already read — and write — most patterns you'll run into.

1. The dot: match anything

. matches any single character except a line break. c.t matches cat, cot, and c9t — the dot doesn't care what's there, only that something is.

2. Quantifiers: how many times

These three control repetition, and they're the ones people mix up most:

  • * — zero or more. lo*l matches ll, lol, loool.
  • + — one or more. lo+l matches lol and loool, but not ll.
  • ? — zero or one, making the thing before it optional. colou?r matches both color and colour.

3. Character classes: pick from a set

Square brackets mean "match one character from this set." [aeiou] matches any single vowel. Add a dash for a range: [0-9] matches any digit, [a-zA-Z] matches any letter regardless of case.

Shortcuts worth knowing: \d means the same thing as [0-9], \w matches any letter/digit/underscore, and \s matches whitespace. They're just character classes with a shorter name.

4. Anchors: where in the string

^ anchors to the start of the string, $ anchors to the end. ^Error only matches lines that begin with "Error" — not ones where "Error" shows up in the middle of a sentence.

5. Groups and alternation

Parentheses () group part of a pattern together, and the pipe | means "or." (cat|dog) matches either word. Combine it with the rest: gr(a|e)y matches both gray and grey in one pattern.

Putting it together

A pattern to match a basic US phone number: \d{3}-\d{3}-\d{4} — three digits, a dash, three digits, a dash, four digits. Once you can read \d as "a digit" and {3} as "exactly three of the last thing," patterns like this stop looking cryptic and start looking like a sentence.

Comments