Matcher 在 Java 中使用 usePattern() 方法(附示例)
java.util.regex.Matcher 类表示执行各种匹配操作的引擎。该类没有构造函数,可以使用 java.util.regex.Pattern 类的 matches() 方法创建/获取该类的对象。
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 = "[#%&*]";
//Creating a pattern object
Pattern pattern = Pattern.compile(regex);
//Creating a Matcher object
Matcher matcher = pattern.matcher(input);
int count =0;
while(matcher.find()) {
count++;
}
//Retrieving Pattern used
System.out.println("The are "+count+" special characters [# % & *] in the given text");
//Building a pattern to accept 5 t 6 characters
Pattern newPattern = Pattern.compile("\A(?=\w{6,15}\z)");
//Switching to new pattern
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
广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP