1. Match Zero or One Occurrence Using ?
This program demonstrates the ? quantifier in Java regular expressions. The ? matches zero or one occurrence of the preceding character or group. It matches the character when it is present but does not require it.
import java.util.regex.*;
public class ZeroOrOneMatch {
public static void main(String[] args) {
String input = "color colour";
Pattern pattern = Pattern.compile("colou?r");
Matcher matcher = pattern.matcher(input);
while (matcher.find()) {
System.out.println("Matched: " + matcher.group());
}
}
}Output:
Matched: color
Matched: colour
2. Match an Optional Character Using ?
This program uses ? to make the character u optional in the pattern. The pattern can match both color and colour. Thus, ? allows the preceding character to occur either zero or one time.
import java.util.regex.*;
public class OptionalCharacterMatch {
public static void main(String[] args) {
String input = "color colour";
Pattern pattern = Pattern.compile("colou?r");
Matcher matcher = pattern.matcher(input);
while (matcher.find()) {
System.out.println("Matched: " + matcher.group());
}
}
}Output:
Matched: color
Matched: colour
