Hone

Lessons · Regex · character classes

One character from a set

[abc] matches one of a, b or c; [a-z] a range; \d \w \s are digits, word characters, whitespace.

Hone is a place to practise programming. This is one of its lessons, written out in full and free to read without an account.

What it is for

Hex codes, postcodes, ids, phone numbers: fixed alphabets with fixed lengths.

How to think about it

Which characters are allowed, and how many? Describe one character, then say how many with a quantifier: [0-9a-f]{6}.

Worked example

pattern: ^[A-Z]{2}\d{4}$
Two capitals then four digits.
text: AB1234
Match.
text: A1234
No match: only one capital.

Your turn

A vowel.

[]

The trap

Inside [...] most specials are literal, but ^ at the start means 'not': [^0-9] is a non-digit.

Practise character classes on HoneA question on it now, a coding challenge where there is one, and it is remembered for review. Free, no email needed.