Character Classes and Ranges
Understanding Character Classes
Character classes allow you to define a set of characters to match. They are enclosed in square brackets [ ]. Any single character within the brackets will match. For example, [abc] will match any occurrence of ‘a’, ‘b’, or ‘c’.
const regex = /[abc]/;
console.log(regex.test('apple')); // true (matches 'a')
console.log(regex.test('banana')); // true (matches 'a')
console.log(regex.test('cherry')); // true (matches 'c')
console.log(regex.test('date')); // false (no match)Using Ranges within Character Classes
Ranges allow you to specify a range of characters using a hyphen -. For example, [a-z] matches any lowercase letter from ‘a’ to ‘z’.
const regex = /[a-z]/;
console.log(regex.test('apple')); // true (matches 'a')
console.log(regex.test('Banana')); // true (matches 'a', 'n')
console.log(regex.test('12345')); // false (no match)You can combine ranges and individual characters within a single character class:
const regex = /[a-zA-Z0-9]/;
console.log(regex.test('apple')); // true (matches 'a')
console.log(regex.test('Banana')); // true (matches 'B')
console.log(regex.test('12345')); // true (matches '1')
console.log(regex.test('!@#$%')); // false (no match)Predefined Character Classes
JavaScript provides several predefined character classes for common sets of characters:
\d: Matches any digit (equivalent to[0-9])\D: Matches any non-digit\w: Matches any word character (alphanumeric + underscore, equivalent to[a-zA-Z0-9_])\W: Matches any non-word character\s: Matches any whitespace character (space, tab, newline)\S: Matches any non-whitespace character
const regexDigit = /\d/;
console.log(regexDigit.test('123')); // true (matches '1')
console.log(regexDigit.test('abc')); // false (no match)
const regexNonDigit = /\D/;
console.log(regexNonDigit.test('123')); // false (no match)
console.log(regexNonDigit.test('abc')); // true (matches 'a')
const regexWord = /\w/;
console.log(regexWord.test('hello_world123')); // true (matches 'h')
console.log(regexWord.test('!@#$%')); // false (no match)
const regexWhitespace = /\s/;
console.log(regexWhitespace.test('hello world')); // true (matches space)
console.log(regexWhitespace.test('helloworld')); // false (no match)Exercises
- Write a regular expression that matches any lowercase letter.
- Create a Regex pattern that matches any digit and any uppercase letter.
- Write a regular expression that matches any non-word character.
Character classes and ranges are powerful tools for defining sets of characters in your patterns.