正則表示式 a|b 元字元在 Java 中


子表示式/元字元“a| b”匹配 a 或 b。

示例 1

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 Tutorialspoint";
      Pattern p = Pattern.compile(regex);
      Matcher m = p.matcher(input);
      int count = 0;
      while(m.find()) {
         count++;
      }
      System.out.println("Number of matches: "+count);
   }
}

輸出

Number of matches: 2

示例 2

以下 Java 程式從使用者讀取性別值,並且只允許 M(男性)、F (女性) 或 O(其他)。

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 to match M or, F or, O
      String regex = "M|F|O";
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter students 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");
      }
   }
}

輸出 1

Enter students gender:
M
All OK

輸出 2

Enter students gender:
male
Wrong Input

更新於: 19-Nov-2019

319 次瀏覽

啟動你的職業

完成課程並獲得認證

開始
廣告
© . All rights reserved.