Java 中帶示例的 Pattern CASE_INSENSITIVE 欄位


Pattern 類的此 CASE_INSENSITIVE 欄位匹配不分大小寫的字元。當您使用它作為 compile() 方法的標誌值時,並且如果使用正則表示式搜尋字元,那麼兩種大小寫的字元都將匹配。

注意 - 預設情況下,此標誌僅匹配 ASCII 字元

示例 1

import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class CASE_INSENSITIVE_Example {
   public static void main( String args[] ) {
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter input data: ");
      String input = sc.nextLine();
      System.out.println("Enter required character: ");
      char ch = sc.next().toCharArray()[0];
      //Regular expression to find the required character
      String regex = "["+ch+"]";
      //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("The letter "+ch+" occurred "+count+" times in the given text (irrespective of case)");
   }
}

輸出

Enter input data:
Tutorials Point originated from the idea that there exists a class 
of readers who respond better to online content and prefer to learn 
new skills at their own pace from the comforts of their drawing rooms.
Enter required character:
T
The letter T occurred 20 times in the given text (irrespective of case)

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

輸出 1

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

輸出 2

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

輸出 3

Enter a string value:
hello
Given string is not a boolean type

更新於:20-Nov-2019

2K+ 瀏覽

開啟你的 職業生涯

透過完成課程獲取認證

開始
廣告
© . All rights reserved.