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

Regular Expressions Meta Character a | b in Java

Subexpression/Meta character " a | b Match a or b.

Example1

import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RegexExample {
   public static void main(String args[]) {
      String regex = "Hello|welcome";
      String input = "Hello how are you welcome to the"3codebox";
      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: 2

Example2

The following Java program reads a gender value from the user and allows only M (male), F (female), or O (other).

import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RegexExample {
   public static void main(String args[]) {
      //Regular expression matches M or F or O-
      String regex = "M|F|O";
      Scanner sc = new Scanner(System.in);
      System.out.println("Please enter the student's gender:");
      String name = sc.nextLine();
      Pattern p = Pattern.compile(regex);
      Matcher m = p.matcher(name);
      if(m.matches()) {
         System.out.println("All OK");
      } else {
         System.out.println("Wrong Input");
      }
   }
}

Output1

Please enter the student's gender:
M
All OK

Output2

Please enter the student's gender:
male
Wrong Input