C.W.K.
Stream
Lesson 04 of 12 · published

Ranges [a-z] [A-Z] [0-9] — The Hyphen Trick

~6 min · ranges, ascii

Level 0Pattern-Curious
0 XP0/90 lessons0/15 achievements
0/100 XP to next level100 XP to go0% complete

Hyphen between two characters means range

[a-z] is the same as [abcdefghijklmnopqrstuvwxyz], but you'd never write the long form. The hyphen between two characters defines a range based on the underlying character codes (ASCII / Unicode codepoints).

The big three you'll use constantly:

  • [0-9] — any digit (ASCII)
  • [a-z] — any lowercase ASCII letter
  • [A-Z] — any uppercase ASCII letter

You combine them: [a-zA-Z0-9] is alphanumeric. [a-fA-F0-9] is hexadecimal. [가-힣] is Korean Hangul syllables (the entire syllable block).

Don't be clever with ranges

Ranges work on whatever the codepoint order is. [A-z] looks like "any letter" but actually includes the punctuation between Z (90) and a (97): [ \ ] ^ _ `. This is a real bug class. Always write both halves: [A-Za-z].

Hyphen at start, end, or escaped is literal

To match a literal hyphen inside a class, put it first ([-a-z]), last ([a-z-]), or escape it ([a\-z]). Anywhere else, it forms a range. Most style guides put it first or last for clarity.

Code

Ranges in action·python
import re

# A 4-digit year
re.findall(r'[0-9]{4}', 'born 1989, today 2026')
# ['1989', '2026']

# A hex color
re.findall(r'#[0-9a-fA-F]{6}', 'theme #FF8FBE on #000000')
# ['#FF8FBE', '#000000']

# Korean Hangul syllable block
re.findall(r'[가-힣]+', '안녕 hello 세상')
# ['안녕', '세상']

# Bug: [A-z] includes ASCII punctuation
re.findall(r'[A-z]', 'A_z`')
# ['A', '_', 'z', '`']  — '_' and '`' surprise you

External links

Exercise

Write the smallest character class that matches any character in a US license plate (uppercase letters and digits only). Then write one for a Korean license plate (digits, hangul). Compare the patterns — which one needs Unicode support, and which is pure ASCII?

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.