The subexpression/metacharacter “re?” matches 0 or 1 occurrence of the preceding expression.
Example 1
import java.util.regex.Matcher; import java.util.regex.Pattern; public class RegexExample { public static void main( String args[] ) { String regex = "Wel?"; String input = "Welcome to Tutorialspoint"; Pattern p = Pattern.compile(regex); Matcher m = p.matcher(input); int count = 0; while(m.find()) { count++; } System.out.println("Number of matches: "+count); } }
Output
Number of matches: 1
Example 2
Following Java program accepts a string from the user, verifies whether it contains alphabet (both cases), It also accepts digits.
import java.util.Scanner; import java.util.regex.Matcher; import java.util.regex.Pattern; public class Test { public static void main( String args[] ) { String regex = "[a-zA-Z][0-9]?"; Scanner sc = new Scanner(System.in); System.out.println("Enter an input string: "); String input = sc.nextLine(); //Creating a Pattern object Pattern p = Pattern.compile(regex); //Creating a Matcher object Matcher m = p.matcher(input); if(m.find()) { System.out.println("Match occurred"); } else { System.out.println("Match not occurred"); } } }
Output 1
Enter an input string: sample text Match occurred
Output 2
Enter an input string: sample text 34 56 Match occurred
Output 3
Enter an input string: 32 89 45 63 Match not occurred