Course contentsShow
← Java
Lesson 2299 of 2,87044. Regular ExpressionsFree lesson

Union and Intersection in Character Classes

Combine multiple ranges with union ([a-z0-9]) and use intersection ([a-z&&[^aeiou]]) for complex sets.

Union and Intersection in Character Classes

What you'll learn: How to combine multiple character ranges using union and create more precise matching with intersection operators in regex character classes.

The Core Idea

When building character classes, you're not limited to single ranges or simple lists. Java's regex engine lets you combine multiple sets (union) or find overlap between sets (intersection) to create powerful, precise patterns.

Union is straightforward—simply list multiple ranges or characters inside one set of brackets, and any character matching any of those ranges will match. Intersection uses the special && operator to match only characters that appear in both sets.

Union: Combining Sets

Union happens automatically when you list multiple ranges or characters:

Pattern pattern = Pattern.compile("[a-z0-9]");
// Matches any lowercase letter OR any digit
Pattern vowelOrDigit = Pattern.compile("[aeiou0-9]");
// Matches vowels OR digits

Think of union as "or"—the character can be from this set or that set.

Intersection: Narrowing Down

Intersection uses && to match only characters in the overlap:

Pattern consonant = Pattern.compile("[a-z&&[^aeiou]]");
// Matches lowercase letters AND excludes vowels
// Result: only lowercase consonants
Pattern hexUpper = Pattern.compile("[A-F0-9&&[0-9A-C]]");
// Matches characters that are BOTH in [A-F0-9] AND in [0-9A-C]
// Result: 0-9, A, B, C (excludes D, E, F)

Think of intersection as "and"—the character must satisfy both conditions simultaneously.

Practical Example

Pattern alphanumericNoVowels = Pattern.compile("[a-zA-Z0-9&&[^aeiouAEIOU]]");
// Matches letters or digits, but excludes all vowels

Key Takeaway: Use union (simply listing ranges together) when you want characters from any of several sets, and use intersection (&&) when you need characters that belong to all specified sets simultaneously—perfect for creating precise, complex character filters.