如何使用 Java 正則表示式匹配給定字串中一個字元,包括區分大小寫


java.util.regex 包提供以下各種類,以便在字元序列中查詢特定的模式。此包中的 pattern 類是正則表示式的編譯表示形式。

若要匹配給定的輸入字串中的某個特定字元,步驟如下:

  • 獲取輸入字串。

  • 此類的 compile() 方法接收一個表示正則表示式的字串值和一個表示標誌的整數值,並返回 Pattern 物件。透過以下方式編譯正則表示式:

    • 使用所需字元的模式匹配器“[]”,例如:“[t]”。

    • CASE_INSENSITIVE 標誌用於忽略大小寫。

  • Pattern 類的 matcher() 方法接收一個輸入字串並返回 Matcher 物件。使用此方法來建立/檢索匹配器物件。

  • find() - 使用 Matcher 的 find() 方法查詢匹配項。

示例

import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class CompileExample {
   public static void main( String args[] ) {
      //Reading string value
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter input string");
      String input = sc.nextLine();
      //Regular expression to find digits
      String regex = "[t]";
      //Compiling the regular expression
      Pattern pattern = Pattern.compile(regex, Pattern.CASE_INSENSITIVE);
      //Retrieving the matcher object
      Matcher matcher = pattern.matcher(input);
      int count = 0;
      while(matcher.find()) {
         count++;
      }
      System.out.println("Number of matches: "+count);
   }
}

輸出

Enter input string
Tutorialspoint
Number of matches: 3

更新日期: 19-Nov-2019

336 次瀏覽

開啟您的職業生涯

完成課程後獲得認證

開始學習
廣告