确定匹配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
热门推荐
5 短祝福语简短暖心
10 结婚祝福语粤语大全简短
11 晚上祝福语女生文案简短
12 法语妈妈生日祝福语简短
13 药厂开工祝福语大全简短
14 蛋糕节日祝福语简短英文
15 跨年的生日祝福语简短
16 文案祝福语英文短句简短
17 在家聚餐婚礼祝福语简短
18 学生节祝福语大全简短