确定匹配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 儿童毕业祝福语 简短6
14 开工仪式横幅祝福语简短
15 孩子日常祝福语大全简短
16 清晨寄语诗句祝福语简短
17 结婚送亲认亲祝福语简短
18 虎年喝酒拜年祝福语简短