Character Classes
Match any single character from a defined set using square brackets.· 7 min
Concept
A character class [abc] matches any one character from the set inside the brackets. You can use ranges for convenience: [a-z] matches any lowercase letter, [0-9] any digit, [A-Za-z] any letter.
Prefixing with ^ inside the brackets negates the class: [^0-9] matches any character that is NOT a digit.
Shorthand classes are common shortcuts:
- \d — digit, same as [0-9]
- \w — word character: letters, digits, underscore [A-Za-z0-9_]
- \s — whitespace: space, tab, newline
- . — any character except newline (no backslash needed)
For the negated versions, use uppercase: \D, \W, \S match the opposite.
/[aeiou]/gMatches any lowercase vowel
/\d/gMatches any single digit (same as [0-9])
/[^aeiou\s]/gMatches any character that is not a vowel or whitespace
Exercise
Write a pattern that matches any single digit (0 through 9).
Your pattern: