Skip to content
Character Classes [abc] and [a-z]
step 1/5

Reading — step 1 of 5

Read

~1 min readBasic Matching

Character Classes [abc] and [a-z]

A character class is a set of characters that match at a position:

PatternMatches
[abc]a, b, or c
[a-z]any lowercase letter
[A-Za-z0-9]letter or digit
[^abc]anything EXCEPT a, b, c
[\d]digit (escapes work inside)
[]]literal ] (special parsing rule)
[a\-b]literal -, a, or b

Parsing rules:

  • ] ends the class (except as the FIRST char or right after ^)
  • ^ at the start negates
  • - is range syntax UNLESS it's the first/last char or escaped
  • Escapes work inside ([\d-] = digit or hyphen)

Internally a character class is just a set or a bitmap of chars:

python

This single change makes regex substantially more useful: [a-zA-Z_][a-zA-Z0-9_]* is the classic identifier matcher.

Discussion

Ask a question, share an insight, or help someone who’s stuck.

Sign in to post a comment or reply.

Loading…