Java中的Matcher usePattern()方法与示例
java.util.regex.Matcher类表示执行各种匹配操作的引擎。该类没有构造函数,可以使用matches()类java.util.regex.Pattern的方法创建/获取该类的对象。
Matcher类的usePattern()方法接受一个表示新正则表达式模式的Pattern对象,并使用它查找匹配项。
示例
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class UsePatternExample {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter input text: ");
String input = sc.nextLine();
String regex = "[#%&*]";
//创建一个模式对象
Pattern pattern = Pattern.compile(regex);
//创建一个Matcher对象
Matcher matcher = pattern.matcher(input);
int count =0;
while(matcher.find()) {
count++;
}
//检索使用的模式
System.out.println("The are "+count+" special characters [# % & *] in the given text");
//建立一个接受5t6字符的模式
Pattern newPattern = Pattern.compile("\\A(?=\\w{6,15}\\z)");
//切换到新模式
matcher = matcher.usePattern(newPattern);
if(matcher.find()) {
System.out.println("Given input contain 6 to 15 characters");
} else {
System.out.println("Given input doesn't contain 6 to 15 characters");
}
}
}输出结果
Enter input text: #*mypassword& The are 3 special characters [# % & *] in the given text !!mypassword! Given input doesn't contain 6 to 15 characters
热门推荐
10 新年门口花束祝福语简短
11 盘锦结婚祝福语大全简短
12 父母生日祝福语 简短独特
13 家庭恩爱祝福语简短英文
14 高考俄语祝福语大全简短
15 虎年祝福语 诗句唯美简短
16 生日婚礼祝福语简短精辟
17 虎年喝酒拜年祝福语简短
18 教师闺蜜祝福语简短