Java中的Matcher regionEnd()方法与示例
java.util.regex.Matcher类表示执行各种匹配操作的引擎。此类没有构造函数,可以使用matches()类java.util.regex.Pattern的方法创建/获取此类的对象。
此类(Matcher)的regionEnd()方法返回一个整数值,该整数值表示当前匹配器对象的结束索引。
例子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.";
//创建一个模式对象
Pattern pattern = Pattern.compile(regex);
//创建一个Matcher对象
Matcher matcher = pattern.matcher(input);
//设置匹配器的区域
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());
}
}输出结果
Match not found End of the region: 20
例子2
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RegionEndExample {
public static void main(String[] args) {
//正则表达式可以接受6到10个字符
String regex = "[#]";
System.out.println("Enter a string: ");
Scanner sc = new Scanner(System.in);
String input = sc.nextLine();
//创建一个模式对象
Pattern pattern = Pattern.compile(regex);
//创建一个Matcher对象
Matcher matcher = pattern.matcher(input);
//将区域设置为输入字符串
matcher.region(2, 4);
//切换到透明范围
if(matcher.find()) {
System.out.println("Match found");
} else {
System.out.println("Match not found");
}
System.out.println("Ending of the region: "+ matcher.regionEnd());
}
}输出结果
Enter a string: this is sample text # Match not found Ending of the region: 4
热门推荐
1 如何训练狗狗不叫
2 训练狗狗不叫
3 训练狗狗随行
4 怎么训练狗狗不叫
7 训练比熊狗狗教程
10 上海狗狗训练
11 怎么训练狗狗上厕所
12 训练狗狗趴下
13 狗狗服从训练
14 训练狗狗拒食
15 训练狗狗笑
16 训练狗狗大便
17 训练狗狗立
18 训练狗狗捡东西