Chuyển đến nội dung

Bài 4 · Getting Started

Reading and Writing Your First Patterns

A practical method for reading any regular expression piece by piece and for building your own, from sample text to a tested pattern, with worked examples for dates, times and IDs.

A regex looks like noise at first: ^(\d{3})-(\d{4})$. The trick is that you never read it all at once. You read it left to right, one token at a time, the same way the engine does. This lesson gives you a method for reading patterns, a method for writing them, and a handful of worked examples.

Reading: split into tokens

Take a pattern and cut it into tokens. A token is a single thing: a literal character, an escape like \d, a class like [a-f], a group ( ... ), an anchor, and each can be followed by a quantifier.

Pattern: ^[A-Z]{2}\d{4}$

Token Meaning
^ start of the text
[A-Z] one uppercase letter
exactly twice (applies to the class before it)
\d one digit
exactly four times
$ end of the text

So the pattern means: two capital letters, then four digits, and nothing else. AB1234 matches; AB12345 and ab1234 do not.

Node.js Test a pattern you just read

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

A quantifier (+, *, ?, ) always applies to the single token right before it. In ab+, only b repeats. To repeat ab, use a group: (ab)+.

Writing: from samples to a pattern

A reliable recipe for writing a regex:

  1. Collect samples of what must match, and of what must not.
  2. Find the fixed parts (literals like -, : or @).
  3. Describe the variable parts by type and count (digits, letters, how many).
  4. Combine them in order, then anchor if you are validating.
  5. Run the samples, fix, repeat.

Example: a time like 09:45

Samples to match: 09:45, 23:59, 00:00. Not to match: 9:45, 24:00, 12:60, 12:5.

Start simple, then tighten.

Node.js Growing a pattern in steps

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Notice how each version removes one class of wrong answers. This is the normal workflow: begin permissive, add constraints until the bad samples fail.

Common reading mistakes

  • Reading a class as a sequence. [abc] matches one character that is a, b or c, not the text "abc".
  • Forgetting that . is a wildcard. In 3.14, the dot matches any character, so 3x14 matches too. Escape it: 3\.14.
  • Forgetting the engine is left to right and greedy. a.*b finds the last b, not the first. We cover this in the quantifier chapter.
  • Ignoring flags. /abc/i and /abc/ are different patterns.
Node.js Class versus sequence, dot versus escaped dot

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Documenting your pattern

Regexes are hard to read later. Three habits help:

  1. Name the pattern with a good variable name (isoDate, hexColor).
  2. Build big patterns from small named pieces with RegExp and String.raw.
  3. Add a comment with an example line it matches.
Node.js Compose a pattern from named parts

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The last line is a useful lesson: a regex checks the shape of text. 2026-02-31 has a valid shape but is not a real date. Use Date or a date library for real calendar checks, and a regex for the quick first filter.

flowchart LR
  A["Samples: good and bad"] --> B["Draft a loose pattern"]
  B --> C["Run all samples"]
  C --> D{"All correct?"}
  D -- "no" --> E["Tighten or loosen one piece"]
  E --> C
  D -- "yes" --> F["Name it, comment it, keep the tests"]

The write-test-adjust loop is how regexes are built in practice.

Check your understanding

Quick check · 4 questions

of 4 answered You scored / 4 · perfect!

  1. 1. In ^[A-Z]{2}\d{4}$, what does apply to?

    A quantifier applies to the single token immediately before it, here the class [A-Z].
  2. 2. Does /[abc]/ match the text 'abc' as a whole word?

    A character class matches exactly one character out of its set.
  3. 3. Why does /3.14/ match '3x14'?

    An unescaped dot matches any character except a line break. Use \. to match a literal dot.
  4. 4. What is the best first step when writing a new regex?

    Samples define what correct means. You can then grow the pattern and test it against them.

Summary

  • Read patterns token by token; a quantifier applies to the single token before it.
  • Write patterns from samples: fixed parts, variable parts, anchors, then test and tighten.
  • Beware of class-versus-sequence and unescaped dots.
  • Build large patterns from named parts, and remember that a regex checks shape, not meaning.

Next: Literals, Escaping and the Dot

Theo dõi tiến độ của bạn

Tạo tài khoản miễn phí để đánh dấu bài đã học và tiếp tục từ chỗ bạn dừng lại trên mọi thiết bị.