C.W.K.
Stream
Lesson 08 of 10 · published

Regular Expressions Basics

~15 min · regex, patterns

Level 0Window Tourist
0 XP0/95 lessons0/14 achievements
0/100 XP to next level100 XP to go0% complete

The pattern language inside every text tool

Regex appears in grep, sed, awk, vim, your editor's find dialog, and every modern programming language. The dialects vary; the core grammar is stable.

Building blocks

  • Any character: .
  • Character class: [abc] = a, b, or c. [^abc] = anything but. [a-z] = range.
  • Predefined: \d digit (PCRE), \w word, \s whitespace.
  • Anchors: ^ start of line, $ end. \b word boundary (PCRE).

Quantifiers

  • * — 0 or more.
  • + — 1 or more (ERE/PCRE).
  • ? — 0 or 1 (ERE/PCRE).
  • {3} — exactly 3.
  • {2,5} — 2 to 5.

Grouping and alternation

  • (foo|bar) — foo or bar.
  • (\d+) — capture digits, refer back as \1.

BRE vs ERE vs PCRE

  • BRE (basic, default for grep/sed) — +, ?, {}, and () need backslashes.
  • ERE (extended, grep -E, sed -E) — the modern, sane dialect.
  • PCRE (Perl-compatible, grep -P) — full power: lookahead, lookbehind, named groups.

Practical patterns

  • Email-ish: [A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}
  • IP-ish: \b(\d{1,3}\.){3}\d{1,3}\b
  • ISO date: \d{4}-\d{2}-\d{2}
  • Trailing whitespace: [[:space:]]+$

Real email validation is a nightmare; that pattern is just a strong filter. Don't try to write a perfect regex for human languages.

Code

Test patterns with grep -E·bash
echo 'visit https://example.com today' \
  | grep -oE 'https?://[A-Za-z0-9./_-]+'
echo '2026-04-15: meeting at 10:00' \
  | grep -oE '\d{4}-\d{2}-\d{2}'
echo 'a1b2c3' | grep -oE '[a-z][0-9]'

External links

Exercise

Pull every URL from a file: grep -oE 'https?://[^ ]+' notes.md. Pull every ISO date from a log: grep -oE '\d{4}-\d{2}-\d{2}' app.log | sort -u. Test on regex101.com to see how each pattern decomposes.

Progress

Progress is local-only — sign in to sync across devices.
Spotted a bug or have feedback on this page?Report an Issue

Comments 0

🔔 Reply notifications (sign in)
Sign inPlease sign in to comment.

No comments yet — be the first.