Negated Character Classes: [^...]
You'll learn how to match any character except those you specify using the caret (^) inside square brackets.
When you place a caret (^) as the first character inside square brackets [^...], you flip the meaning of the character class. Instead of matching characters in the set, the pattern matches any character not in the set.
The Core Idea
Think of it like a VIP list at a club: [abc] says "only these people get in," while [^abc] says "everyone except these people gets in."
The syntax is simple:
[abc]matches 'a', 'b', or 'c'[^abc]matches any character except 'a', 'b', or 'c'
Common Use Cases
import java.util.regex.*;
// Match any non-digit character
Pattern nonDigit = Pattern.compile("[^0-9]");
Matcher m1 = nonDigit.matcher("abc123");
// Finds: 'a', 'b', 'c' (not the digits)
// Match any non-vowel
Pattern nonVowel = Pattern.compile("[^aeiouAEIOU]");
Matcher m2 = nonVowel.matcher("Hello");
// Finds: 'H', 'l', 'l' (consonants)
// Remove all non-alphanumeric characters
String cleaned = "hello@world!123".replaceAll("[^a-zA-Z0-9]", "");
// Result: "helloworld123"
Important Note
The ^ only negates when it's the first character inside brackets. Anywhere else, it's just a literal caret character:
[^abc]→ negated class (not a, b, or c)[a^bc]→ literal class (matches a, ^, b, or c)
Key Takeaway: Use [^...] to match any character not in the specified set—perfect for filtering out unwanted characters or finding "everything except" a specific group.