Regex for People Who Keep Copy-Pasting It Off Forums

Regex for People Who Keep Copy-Pasting It Off Forums

Tutorials javascript programming regex tutorial

I've been meaning to write this one since December, when I was helping my cousin debug a contact form on his half-finished portfolio site and realized he'd never actually been taught what regular expressions even are. He just copy-pasted something off a forum and prayed. Which, honestly, is how most of us start with regex, so no judgment. But let's actually go through it this time instead of just pasting magic symbols.

A regular expression (regex, for short) is just a pattern you use to match text. That's it. It's not a language, not really a "feature" of any one tool, it shows up in JavaScript, PHP, Python, grep, your text editor's find-and-replace, pretty much everywhere. Once you know the basics you can use them anywhere, which is the main reason it's worth the hour or two of pain to learn.

The building blocks

Most characters in a regex just match themselves. The pattern cat matches the literal text "cat." Boring, but that's the baseline. The interesting stuff is the special characters:

  • . matches any single character (except a newline, usually)
  • * means "zero or more of the thing before it"
  • + means "one or more"
  • ? means "zero or one" (optional)
  • \d matches a digit, \w matches a word character (letters, digits, underscore), \s matches whitespace
  • [] defines a set of characters, like [aeiou] for any vowel
  • ^ and $ anchor to the start and end of a string

Stack those together and you can describe surprisingly complicated patterns in one line. That's the whole appeal and also why regex gets a bad reputation, a dense pattern looks like line noise if you don't know what you're looking at. I still write mine slowly, testing piece by piece, and I've been doing this for years.

Example 1: stripping whitespace

This is the one you'll actually use constantly. Say someone pastes text into a form field and it's got leading and trailing spaces (or worse, tabs) that you want gone before you save it anywhere. In JavaScript:

var cleaned = userInput.replace(/^\s+|\s+$/g, "");

Break that down: ^\s+ matches one or more whitespace characters right at the start of the string, \s+$ matches the same thing at the end, and the | means "match either of these." The g flag at the end says "do this globally," so it doesn't just quit after the first match. Newer JS engines are starting to ship a native .trim() method that does the same thing without regex at all, which is nice, but plenty of code out there (and some older browsers people are still stuck on) doesn't have it, so it's worth knowing the pattern by hand.

Example 2: validating an email address

Everyone eventually needs to check "does this look like an email address." Here's the thing nobody tells beginners: you cannot write a regex that perfectly validates every technically-legal email address per the actual spec. The spec is absurd, technically "much.more unusual"@example.com with a space and quotes in it is valid. Nobody does that. So don't chase perfection, chase "good enough to catch typos."

A reasonable, practical pattern:

var emailPattern = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;

Read it left to right: start of string, one or more characters that aren't whitespace or an @, then a literal @, then more non-whitespace-non-@ characters, then a literal dot, then more of the same, end of string. It'll correctly reject bob@ or not an email or bob@site (no dot), and it'll accept [email protected] and [email protected]. It will also let through some garbage that technically matches the shape but isn't a real address, that's fine, that's what the actual verification email is for. Don't try to solve that problem with a regex, you'll lose.

One thing that trips people up: in most languages you need to escape the dot as \. because an unescaped . matches any character, not just a period. I've seen production code that forgot this and it happily accepted things like bob@examplexcom. Small bug, easy to miss, annoying to track down at 11pm.

Get comfortable with \s, \d, +, *, and anchors, and you can already do most of what you'll ever need day to day. The rest, lookaheads, backreferences, named groups, you can pick up later when you actually hit a wall that needs them. I still had to look up lookahead syntax three separate times before it stuck.