java正则表达式 位置_确定匹配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个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值