Regex Character Classes, Quantifiers & Anchors

By Ramanathan Aug 28, 2026 2 min read Regex Tester

Most regular expressions are built from three kinds of piece: what to match (character classes), how many (quantifiers), and where (anchors). Master these and the rest of regex is mostly combination.

This is a supporting guide in The Complete Guide to Regular Expressions.

Character classes

A character class matches exactly one character from a set:

  • [abc] — an a, b, or c
  • [a-z], [A-Z], [0-9] — ranges
  • [a-zA-Z0-9_] — combine ranges and characters
  • [^...] — negate: [^0-9] is any non-digit

Inside a class most metacharacters lose their special meaning — [.] matches a literal dot, no escaping needed. The characters that still matter inside a class are ^ (only first), - (a range unless first/last), and ].

Shorthand classes

Common sets have shortcuts you'll use constantly:

ShorthandMatchesEquivalent
\da digit[0-9]
\wa word char[A-Za-z0-9_]
\swhitespacespace, tab, newline
\D \W \Sthe negationsnot the above

Quantifiers

Quantifiers repeat the item just before them:

  • * — zero or more
  • + — one or more
  • ? — zero or one (optional)
  • {3} — exactly three
  • {2,5} — between two and five
  • {2,} — two or more

Greedy vs lazy

By default quantifiers are greedy: they match as much as they can, then give back if needed. Add ? to make them lazy (match as little as possible). The classic example is matching inside tags:

Input:  <b>one</b><b>two</b>
<.+>    -> matches the whole line (greedy)
<.+?>   -> matches <b> then </b> ... (lazy, each tag)

Reaching for lazy quantifiers is often the fix when a pattern "matches too much".

Anchors and boundaries

Anchors match a position between characters, not a character itself:

  • ^ — start of the string (or line, with the m flag)
  • $ — end of the string (or line)
  • \b — a word boundary (between \w and non-\w)
  • \B — not a word boundary

^\d{3}-\d{4}$ means "the entire string is 3 digits, a dash, then 4 digits" — the anchors are what stop it from matching that pattern inside a longer string.

Related

Part of The Complete Guide to Regular Expressions. See also Groups, Backreferences & Lookarounds.

Try it

Test these against real text in the Regex Tester — matches highlight live as you type, all in your browser.

About the author

Ramanathan · Software Engineer & Solutions Architect

I'm a Software Engineer and Solutions Architect with 20+ years of experience building enterprise applications across BFSI, Healthcare, Retail, Manufacturing, and Industrial Automation. I've spent those two decades living in JSON, tokens, regexes, and config files — so I built the fast, private, no-login developer tools I always wanted to reach for myself.

Last updated: Aug 28, 2026