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.
regionEnd () phương thức của lớp này (Matcher) trả về một giá trị số nguyên đại diện cho chỉ số cuối của đối tượng so khớp hiện tại.
Ví dụ 1
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RegionEndExample {
public static void main(String[] args) {
String regex = "(.*)(\\d+)(.*)";
String input = "This is a sample Text, 1234, with numbers in between.";
//Creating a pattern object
Pattern pattern = Pattern.compile(regex);
//Creating a Matcher object
Matcher matcher = pattern.matcher(input);
//Setting the region of the matcher
matcher.region(5, 20);
if(matcher.matches()) {
System.out.println("Match found");
} else {
System.out.println("Match not found");
}
System.out.print("End of the region: "+matcher.regionEnd());
}
} Đầu ra
Match not found End of the region: 20
Ví dụ 2
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RegionEndExample {
public static void main(String[] args) {
//Regular expression to accepts 6 to 10 characters
String regex = "[#]";
System.out.println("Enter a string: ");
Scanner sc = new Scanner(System.in);
String input = sc.nextLine();
//Creating a pattern object
Pattern pattern = Pattern.compile(regex);
//Creating a Matcher object
Matcher matcher = pattern.matcher(input);
//Setting region to the input string
matcher.region(2, 4);
//Switching to transparent bounds
if(matcher.find()) {
System.out.println("Match found");
} else {
System.out.println("Match not found");
}
System.out.println("Ending of the region: "+ matcher.regionEnd());
}
} Đầu ra
Enter a string: this is sample text # Match not found Ending of the region: 4