Regular Expressions: Stop Copy-Pasting Patterns You Can't Read · 第 1 / 6 节

Lesson 01: The pattern that matches plain text

Lesson objectives:

  • Say what a regular expression is and what it is matched against.
  • Match plain literal text and read the result of test and match.
  • Tell a literal character from a special one (a metacharacter).

Prerequisites: you can call a method like "text".match(...) in a console | Next 02 >>

The pattern you pasted is just an alphabet you never learned

You have copied regexes that "validate an email" without being able to point at which part does what. That is not a memory problem — nobody handed you the alphabet the pattern is spelled in. A regular expression is a tiny language, and like any language it starts with the boring case: characters that just match themselves. Before \d and .+? can stop looking like line noise, you need the ground floor — what a pattern is matched against, and what "special character" even means. This lesson is only that ground floor, and everything later is built on it.

Explanation

A regular expression (regex) is a pattern used to match combinations of characters inside a string1. You hand the engine two things — a pattern and a string — and it tells you whether, and where, the pattern occurs. In JavaScript you write a pattern between slashes, like /cat/, and the string is whatever you test it against.

The simplest patterns are literals: characters that match themselves. The pattern /cat/ matches the exact sequence "cat" wherever it appears1. That last part matters more than beginners expect — the pattern does not have to equal the whole string. It only has to be found inside it.

You run a pattern with a method. Two you will use constantly: test, which returns true or false for "does this pattern occur anywhere in the string," and match, which returns the actual matched text1. Regexes are used with RegExp methods like test and with String methods like match1.

When match succeeds without the global flag, it returns an array whose element at index 0 is the whole matched text, plus extra properties like index telling you where it was found2. For now, read element 0 as "the substring the pattern matched."

So far every character has been a literal. But some characters are special — they are instructions, not letters. When you need more than a direct match, such as "one or more of something" or "any digit," you use special characters in the pattern1. Characters like ., *, +, ?, ^, $, [, ], (, ), and \ do not match themselves; each is a piece of syntax. These special characters are called metacharacters, and every remaining lesson is really about one small group of them at a time. For now, just hold the split in your head: letters and digits are literals; that handful of punctuation marks are instructions.

Worked example (follow along)

Say you want to know whether a log line mentions an error. Open your browser DevTools console (or a Node REPL) and try:

Step by step: /ERROR/ is five literal characters and none of them are special, so the engine looks for the exact run "ERROR" and does not find it, returning false. /WARN/ is found starting at index 11, so test returns true and match hands back the matched text plus its position. You did nothing clever — you searched for literal text and read the result.

Your turn (faded example)

You want to check whether a filename ends up containing the word "draft". Fill in the one missing piece so the check is a literal search:

Answer: the blank is the literal draft, giving /draft/.test(name). The characters d-r-a-f-t are all literals, so the engine searches for that exact run and finds it inside "report-draft-2.md", returning true. Notice you never had to make the pattern equal the whole filename — a literal pattern matches when it is found anywhere inside the string.

Summary + what's next

A regex is a pattern matched against a string. Literal characters match themselves, and a literal pattern succeeds when it is found anywhere inside the string — it need not equal the whole thing. test returns a boolean; match returns the matched text at element 0. And some characters — the metacharacters — are instructions, not letters. Next we meet the first real metacharacter family: character classes, which let one position in your pattern match a whole set of characters instead of a single fixed letter — and we finally pin down what that . really does.

Footnotes

  1. MDN: Regular expressions (JavaScript Guide) — https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_expressions 2 3 4 5

  2. MDN: String.prototype.match() — https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/match

Exercises

Exercise 1 · Level 1 (warm-up)

Open your browser DevTools console (or run node). Define const s = "the quick brown fox";. Predict, then run, each of these: /quick/.test(s), /QUICK/.test(s), and s.match(/o/).

Done criteria · checked locally
Exercise 2 · Level 2 (advanced)

Still in the console, run "a.b.c".match(/./). You expected the literal dot, but look at what element 0 actually is. Then explain, in one sentence, why the result is what it is.

Done criteria · checked locally