How to match one of the two given expressions using Java RegEx?

JavaObject Oriented ProgrammingProgramming

Using the or logical operator | of Java regular expressions you can match either of two given expressions.

For example, if you need your regular expression should match more than one expression you can do so by separating the required expressions by “|”.

Example 1

import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Example {
   public static void main(String args[]) {
      //Reading String from user
      System.out.println("Enter a String");
      Scanner sc = new Scanner(System.in);
      String input = sc.nextLine();
      //Regular expression to match string that starts with hello or ends with bye
      String regex = "^hello|bye$";
      //Compiling the regular expression
      Pattern pattern = Pattern.compile(regex);
      //Retrieving the matcher object
      Matcher matcher = pattern.matcher(input);
      if(matcher.find()) {
         System.out.println("Match occurred");
      } else {
         System.out.println("Match not occurred");
      }
   }
}

Output 1

Enter a String
hello how are you
Match occurred

Output 2

Enter a String
This is a sample string
Match not occurred

Example 2

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

Output 1

Enter input value:
yes
match occurred

Output 2

Enter input value:
hello
match not accepted
raja
Published on 19-Nov-2019 07:37:24
Advertisements