1. Match a Single Character from [abc]
This program demonstrates how [abc] matches exactly one character from a, b, or c. It checks each character of the input string against the pattern. Characters other than a, b, or c are not matched.
import java.util.regex.*;
public class SingleCharacterMatch {
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: a
2. Find All Characters Matching [abc]
This program searches a string for characters that belong to the set a, b, or c. The regular expression [abc] matches only one character at a time. It displays every matching character found in the input.
import java.util.regex.*;
public class FindMatchingCharacters {
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: b
Matched: a
Matched: a
Matched: a
Matched: c
