1. Match Zero or More Occurrences Using *
This program demonstrates the * quantifier in Java regular expressions. The * matches zero or more occurrences of the preceding character or group. It can match the character even when it occurs zero times.
import java.util.regex.*;
public class ZeroOrMoreMatch {
public static void main(String[] args) {
String input = "aaab";
Pattern pattern = Pattern.compile("a*");
Matcher matcher = pattern.matcher(input);
while (matcher.find()) {
System.out.println("Matched: \"" + matcher.group() + "\"");
}
}
}Output:
Matched: "aaa"
Matched: ""
Matched: ""Code language: JavaScript (javascript)
2. Match Repeated Characters Using *
This program uses * to find zero or more consecutive occurrences of the character b. It matches a group containing one or more b characters as well as an empty match. The program displays each match found in the input string.
import java.util.regex.*;
public class RepeatedCharacterMatch {
public static void main(String[] args) {
String input = "abbcbb";
Pattern pattern = Pattern.compile("b*");
Matcher matcher = pattern.matcher(input);
while (matcher.find()) {
System.out.println("Matched: \"" + matcher.group() + "\"");
}
}
}Output:
Matched: ""
Matched: "bb"
Matched: ""
Matched: "bb"
Matched: ""Code language: JavaScript (javascript)
