确定匹配Java正则表达式的位置和长度
start()java.util.regex.Matcher类的方法返回匹配的开始位置(如果发生匹配)。
同样,end()Matcher类的方法返回匹配的结束位置。
因此,start()方法的返回值将是匹配的开始位置,而end()和start()方法的返回值之间的差将是匹配的长度。
示例
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class MatcherExample {
public static void main(String[] args) {
int start = 0, len = -1;
Scanner sc = new Scanner(System.in);
System.out.println("Enter input text: ");
String input = sc.nextLine();
String regex = "\\d+";
//创建一个模式对象
Pattern pattern = Pattern.compile(regex);
//匹配字符串中的已编译模式
Matcher matcher = pattern.matcher(input);
while (matcher.find()) {
start = matcher.start();
len = matcher.end()-start;
}
System.out.println("Position of the match : "+start);
System.out.println("Length of the match : "+len);
}
}输出结果
Enter input text: sample data with digits 12345 Position of the match : 24 Length of the match : 5
热门推荐
10 财运虎年祝福语简短语
11 单亲爸爸春节祝福语简短
12 狗狗上厕所训练
13 植物种植祝福语简短
14 翻译考试祝福语朋友简短
15 个人周年庆简短祝福语
16 狗狗怎么训练
17 分别祝福语简短搞笑英文
18 生日广州男生祝福语简短