Java 中的 Pattern CASE_INSENSITIVE 字段示例

javaobject oriented programmingprogramming更新于 2024/5/7 5:32:17

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("输入输入数据:");
      String input = sc.nextLine();
      System.out.println("输入所需字符:");
      char ch = sc.next().toCharArray()[0];
      //使用正则表达式查找所需字符
      String regex = "["+ch+"]";
      //编译正则表达式
      Pattern pattern = Pattern.compile(regex, Pattern.CASE_INSENSITIVE);
      //检索匹配器对象
      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("输入一个字符串值:");
      String str = sc.next();
      Pattern pattern = Pattern.compile("true|false", Pattern.CASE_INSENSITIVE);
      Matcher matcher = pattern.matcher(str);
      if(matcher.matches()){
         System.out.println("给定的字符串是布尔类型");
      } else {
         System.out.println("给定的字符串不是布尔类型");
      }
   }
}

输出 1

输入字符串值:
true
给定的字符串是布尔类型

输出 2

输入字符串值:
false
给定的字符串是布尔类型

输出 3

输入字符串值:
hello
给定的字符串不是布尔类型

相关文章


有用资源