如何使用 Java 正则表达式匹配字符串而不考虑大小写。

javaobject oriented programmingprogramming更新于 2024/5/12 23:40:17

patter 类的 compile 方法接受两个参数 −

  • 表示正则表达式的字符串值。
  • 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

相关文章


有用资源