如何使用 Java RegEx 匹配兩個給定表示式中的一個表示式?


使用 Java 正則表示式的 or 邏輯運算子 | 可以匹配兩個給定表示式中的任意一個表示式。

例如,如果你需要讓你的正則表示式匹配多個表示式,可以透過使用“|”將需要的表示式分隔開來。

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

輸出 1

Enter a String
hello how are you
Match occurred

輸出 2

Enter a String
This is a sample string
Match not occurred

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

輸出 1

Enter input value:
yes
match occurred

輸出 2

Enter input value:
hello
match not accepted

更新時間: 19 日 11 月 2019

1 千 + 次瀏覽

開啟您的 職業生涯

完成課程獲得認證

開始
廣告
© . All rights reserved.