Back to roadmaps regex Course

Character Classes: Defining Custom Match Sets

Character classes let you define a custom set of characters to match at a given position.


1. Basic Character Classes

Use square brackets [] to define a set. The pattern matches any single character inside the brackets:

// Match "a", "e", "i", "o", or "u"
/[aeiou]/.test("hello"); // true (matches 'e')
/[aeiou]/.test("rhythm"); // false

2. Character Ranges

Use a hyphen - inside brackets to define a range:

// Match any lowercase letter
/[a-z]/.test("Hello"); // true (matches 'e')

// Match any uppercase letter
/[A-Z]/.test("hello"); // false

// Match any digit or lowercase letter
/[a-z0-9]/.test("user123"); // true

3. Negated Character Classes

Use a caret ^ as the first character inside brackets to match any character not in the set:

// Match any character that is NOT a vowel
/[^aeiou]/.test("rhythm"); // true (matches 'r')

// Match any character that is NOT a digit
/[^0-9]/.test("abc");  // true
/[^0-9]/.test("123");  // false

4. Practical Use Cases

// Validate that a username only contains letters, numbers, and underscores
const isValidUsername = (str) => /^[a-zA-Z0-9_]+$/.test(str);
isValidUsername("user_name_99"); // true
isValidUsername("user name");    // false (space is not allowed)
Published on Last updated: