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