1. Match Characters Not in [abc]
This program demonstrates the use of [^abc] to match a single character that is not a, b, or c. The ^ symbol inside the square brackets negates the character set. It finds and displays characters other than a, b, and c.
import java.util.regex.*;
public class NegatedCharacterMatch {
public static void main(String[] args) {
String input = "apple";
Pattern pattern = Pattern.compile("[^abc]");
Matcher matcher = pattern.matcher(input);
while (matcher.find()) {
System.out.println("Matched: " + matcher.group());
}
}
}Output:
Matched: p
Matched: p
Matched: l
Matched: e
2. Find Characters Excluding [abc]
This program searches a string for characters that are not a, b, or c. The regular expression [^abc] matches one character at a time except the specified characters. It displays all characters that are outside the given character set.
import java.util.regex.*;
public class ExcludeCharacters {
public static void main(String[] args) {
String input = "banana cow";
Pattern pattern = Pattern.compile("[^abc]");
Matcher matcher = pattern.matcher(input);
while (matcher.find()) {
System.out.println("Matched: " + matcher.group());
}
}
}Output:
Matched: n
Matched: n
Matched:
Matched: o
Matched: w
