不管使用Java regex大小写如何匹配字符串。
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();
//正则表达式以查找所需字符
String regex = "test";
//编译正则表达式
Pattern pattern = Pattern.compile(regex);//, Pattern.CASE_INSENSITIVE);
//检索匹配器对象
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
热门推荐
10 50多岁生日简短祝福语
11 简短的出行工作祝福语
12 看病贺卡祝福语简短英文
13 简短大气的狗年祝福语
14 白日庆典祝福语简短英语
15 端午发给客户祝福语简短
16 结婚对白誓言简短祝福语
17 生日贺卡祝福语 简短独特
18 对女友的简短祝福语