Lớp java.util.regex.Matcher đại diện cho một công cụ thực hiện các hoạt động so khớp khác nhau. Không có hàm tạo nào cho lớp này, bạn có thể tạo / lấy một đối tượng của lớp này bằng cách sử dụng phương thức match () của lớp java.util.regex.Pattern.
find () phương thức của lớp này cố gắng tìm đầu vào tiếp theo phù hợp với đối tượng Matcher hiện tại, trong trường hợp khớp phương thức này trả về true, nếu không, phương thức này trả về false.
Ví dụ
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class FindExample {
public static void main( String args[] ) {
//Reading string value
Scanner sc = new Scanner(System.in);
System.out.println("Enter input string");
String input = sc.nextLine();
//Regular expression to find digits
String regex = "(\\D)";
//Compiling the regular expression
Pattern pattern = Pattern.compile(regex);
//Retrieving the matcher object
Matcher matcher = pattern.matcher(input);
//verifying whether match occurred
if(matcher.find()) {
System.out.println("Given string contain non-digit characters");
} else {
System.out.println("Given string does not contain non-digit characters");
}
}
} Đầu ra
Enter input string 11245# Given string contain non-digit characters