Script Valley
Regex: Actually Useful Patterns
Regex FundamentalsLesson 1.3

Character classes and ranges in regex

character class syntax, ranges, negated classes, shorthand classes \d \w \s, combining shorthands

Character Classes Match One of Many

Character classes

Square brackets define a character class โ€” a set of characters where exactly one must match at that position. [aeiou] matches any single lowercase vowel. [0-9] matches any digit via a range shorthand.

/[aeiou]/.test('sky') // false โ€” no vowels
/[aeiou]/.test('the') // true  โ€” 'e' matches

/[a-z]/.test('A')     // false โ€” lowercase only
/[a-zA-Z]/.test('A')  // true  โ€” upper and lower combined

Negated Classes

A caret ^ at the start of a class negates it: match any character NOT in the set.

/[^0-9]/.test('abc') // true  โ€” no digits
/[^0-9]/.test('a1b') // true  โ€” has non-digit chars
/[^a-z]+/.test('123') // true

Shorthand Classes

Three shorthands cover the most common sets:

  • \d โ€” [0-9]
  • \w โ€” [a-zA-Z0-9_]
  • \s โ€” whitespace (space, tab, newline)

Their uppercase inverses negate them: \D matches any non-digit, \W any non-word character, \S any non-whitespace.

/\d{3}/.test('abc')  // false
/\d{3}/.test('123')  // true
/\w+/.test('hello_world') // true

Character classes compose well with quantifiers. [a-z]+ matches one or more lowercase letters; [0-9]{4} matches exactly four digits. You can also mix ranges and individual characters in one class: [a-z0-9_] matches any lowercase letter, digit, or underscore (which is equivalent to \w minus uppercase). When building patterns for identifiers, slugs, or usernames, combining ranges in a single class is cleaner and faster than alternation with multiple sub-patterns.

Up next

Anchors caret and dollar sign in regex

Sign in to track progress

Character classes and ranges in regex โ€” Regex Fundamentals โ€” Regex: Actually Useful Patterns โ€” Script Valley โ€” Script Valley