如何在 Java 中將正則元字元作為文字字元進行匹配。


Pattern 類的 compile 方法有兩個引數 −

  • 一個表示正則表示式的字串值。
  • Pattern 類的域中的一個整數值。

啟用模式的 LITERAL 域用於模式的文字解析。即,所有正則表示式元字元和轉義序列不具有任何特殊含義,它們被視為文字字元。因此,如果你需要將正則表示式元字元作為普通字元進行匹配,則需要將此作為標誌值傳遞給 compile() 方法以及正則表示式。

示例

import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Example {
   public static void main(String[] args) {
      System.out.println("Enter input data: ");
      Scanner sc = new Scanner(System.in);
      String input = sc.nextLine();
      String regex = "^[0-9]";
      //Creating a Pattern object
      Pattern pattern = Pattern.compile(regex, Pattern.LITERAL);
      //Creating a Matcher object
      Matcher matcher = pattern.matcher(input);
      int count = 0;
      while(matcher.find()) {
         count++;
         System.out.println(matcher.group());
      }
      System.out.println("Number of matches: "+count);
   }
}

輸出 1

Enter input data:
9848022338
Number of matches: 0

輸出 2

Enter input data:
^[0-9]
^[0-9]
Number of matches: 1

更新於:21-11-2019

218 次瀏覽

啟動您的職業生涯

透過完成課程獲得認證

立即開始
廣告
© . All rights reserved.