如何使用 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
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP