Combining Classes and Quantifiers
You'll learn how to build powerful, real-world regex patterns by pairing character classes with quantifiers.
Putting the Pieces Together
Now that you understand character classes (what to match) and quantifiers (how many times), it's time to combine them into practical patterns. Think of character classes as your vocabulary and quantifiers as your grammar—together, they form complete sentences that describe the text you're looking for.
When you attach a quantifier to a character class, it applies to any single character from that class, repeated according to the quantifier's rule.
Practical Examples
Matching digits: \d+ matches one or more consecutive digits (like "42" or "12345").
Matching words: \w+ matches sequences of word characters (letters, digits, underscores).
Matching hex colors: #[0-9a-fA-F]{6} matches exactly 6 hexadecimal characters after a hash (like "#FF5733").
Matching variable names: [a-zA-Z_]\w* matches identifiers that start with a letter or underscore, followed by zero or more word characters.
Flexible whitespace: \s+ matches one or more whitespace characters, useful for splitting text where spacing varies.
Real-World Pattern
const phonePattern = /\d{3}-\d{3}-\d{4}/;
phonePattern.test("555-123-4567"); // true
const emailStart = /[a-zA-Z0-9._%+-]+@/;
emailStart.test("user.name@"); // true
The first pattern combines \d with exact quantifiers for phone numbers. The second uses a custom character class with + to match flexible email usernames.
Key Takeaway: Combining character classes with quantifiers lets you describe realistic patterns like "3 digits," "one or more letters," or "any number of word characters"—the foundation of practical regex matching.