English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Explanation of Java regular expression construction “re?”

Subexpression/The meta-character "re?" matches 0 or more occurrences of the preceding expression.1.

Example1

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 w3codebox";
      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 result

Number of matches: 1

Example2

The following Java program accepts a string from the user, verifies whether it contains letters (two cases), and also accepts numbers.

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");
      }
   }
}

Output1

Enter an input string:
sample text
Match occurred

Output2

Enter an input string:
sample text 34 56
Match occurred

Output3

Enter an input string:
32 89 45 63
Match not occurred