patter类的compile方法接受两个参数-
代表正则表达式的字符串值。
一个整数值,是Pattern类的一个字段。
Pattern类的CASE_INSENSITIVE字段与字符匹配,无论大小写如何。因此,如果将标志值compile()
与正则表达式一起传递给方法,则两种情况的字符都将匹配。
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
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