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

How to use Java RegEx to match one of two given expressions?

Using the logical OR operator |, you can match one of the two given expressions in a Java regular expression.

For example, if you need to match multiple expressions with a regular expression, you can separate the required expressions with ' |'.

Example1

import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Example {
   public static void main(String args[]) {
      //Reads a string from the user
      System.out.println("Enter a String");
      Scanner sc = new Scanner(System.in);
      String input = sc.nextLine();
      //The regular expression is used to match strings that start with 'hello' or end with 'bye'.
      String regex = "^hello|bye$";
      //Compile regular expression
      Pattern pattern = Pattern.compile(regex);
      //Retrieve matcher object
      Matcher matcher = pattern.matcher(input);
      if(matcher.find()) {
         System.out.println("Match occurred");
      } else {
         System.out.println("Match not occurred");
      }
   }
}

Output1

Enter a String
hello how are you
Match occurred

Output2

Enter a String
This is a sample string
Match not occurred

Example2

import java.util.Scanner;
public class RegexExample {
   public static void main( String args[] ) {
      //Regular expression to match either yes or no String regex = "yes|no";
      System.out.println("Enter input value: ");
      Scanner sc = new Scanner(System.in);
      String input = sc.nextLine();
      boolean bool = input.matches(regex);
      if(bool) {
         System.out.println("match occurred");
      } else {
         System.out.println("match not accepted");
      }
   }
}

Output1

Enter input value:
yes
match occurred

Output2

Enter input value:
hello
match not accepted