Quantifiers with Character Classes: Practical Patterns
What you'll learn: How to combine quantifiers and character classes to build powerful regex patterns for real-world data like emails, phone numbers, and identifiers.
The Power of Combination
Now that you've learned quantifiers (*, +, ?, {n,m}) and character classes ([...], \d, \w, etc.), the real magic happens when you combine them. Think of quantifiers as the "how many" and character classes as the "what kind"—together, they let you describe realistic patterns like "three or more digits" or "any lowercase letters until you hit a space."
Building Practical Patterns
Simple identifier (variable name):
Pattern pattern = Pattern.compile("[a-zA-Z_]\\w*");
This says: "Start with a letter or underscore, then zero or more word characters." Perfect for validating Java variable names.
U.S. phone number (simple format):
Pattern pattern = Pattern.compile("\\d{3}-\\d{3}-\\d{4}");
Exactly three digits, dash, three digits, dash, four digits.
Basic email-like pattern:
Pattern pattern = Pattern.compile("[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}");
One or more "name characters," an @, one or more domain characters, a dot, then at least two letters for the TLD.
Hexadecimal color code:
Pattern pattern = Pattern.compile("#[0-9A-Fa-f]{6}");
A hash followed by exactly six hex digits.
Why This Matters
Combining quantifiers with character classes lets you express complex, real-world constraints concisely. Instead of checking "is this a digit? Is this a digit? Is this a digit?" manually, you write \d{3} and let the regex engine do the work.
Key Takeaway:
Quantifiers and character classes work together to create precise, practical patterns—use them to validate input formats like identifiers, phone numbers, and other structured data efficiently.