Java中的模式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];
//正则表达式以查找所需字符
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: nhooo.com 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