如何使用 Java 正則表示式在不區分大小寫的情況下匹配字串。


patter 類的編譯方法接受兩個引數 −

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

Pattern 類的 CASE_INSENSITIVE 域欄位匹配不區分大小寫的字元。因此,如果你與你的正則表示式一起將一個標誌值傳遞給 compile() 方法,大小寫字元都將被匹配。

示例 1

import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Example {
   public static void main( String args[] ) {
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter input data: ");
      String input = sc.nextLine();
      //Regular expression to find the required character
      String regex = "test";
      //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 occurrences: "+count);
   }
}

輸出

Enter input data:
test TEST Test sample data
Number of occurrences: 3

示例 2

import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class VerifyBoolean {
   public static void main(String args[]) {
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter a string value: ");
      String str = sc.next();
      Pattern pattern = Pattern.compile("true|false", Pattern.CASE_INSENSITIVE);
      Matcher matcher = pattern.matcher(str);
      if(matcher.matches()){
         System.out.println("Given string is a boolean type");
      } else {
         System.out.println("Given string is not a boolean type");
      }
   }
}

輸出

Enter a string value:
TRUE
Given string is a boolean type

更新於: 2019 年 11 月 21 日

166 次瀏覽

開啟你的 職業生涯

完成該課程即可獲得認證

開始
廣告