java startswinth方法,在Java正则表达式中使用Matcher.start()方法

本文通过一个示例程序详细解释了Java中的Matcher.start()方法,该方法在匹配正则表达式时返回捕获组的起始索引。在给出的代码中,展示了如何使用该方法在字符串'caaabccaab'中查找模式'(a*b)'并打印匹配的起始位置。
摘要由CSDN通过智能技术生成

方法java.util.regex.Matcher.start()返回在上一次匹配操作期间由组找到的子序列的起始索引。此方法有一个参数,即指定模式的捕获组索引。

给出了一个演示方法Matcher.start()Java正则表达式的程序,如下所示:

示例import java.util.regex.Matcher;

import java.util.regex.Pattern;

public class Demo {

public static void main(String args[]) {

Pattern p = Pattern.compile("(a*b)");

Matcher m = p.matcher("caaabccaab");

System.out.println("The input string is: caaabccaab");

System.out.println("The Regex is: (a*b)");

System.out.println();

while (m.find()) {

System.out.println("Index: " + m.start(1));

}

}

}

输出结果The input string is: caaabccaab

The Regex is: (a*b)

Index: 1

Index: 7

现在让我们了解上面的程序。

在字符串序列“ caaabccaab”中搜索子序列“(a * b)”。该find()方法用于查找子序列是否在输入序列中,并使用该start()方法打印在先前的匹配操作期间由组找到的子序列的起始索引。演示此代码段如下:Pattern p = Pattern.compile("(a*b)");

Matcher m = p.matcher("caaabccaab");

System.out.println("The input string is: caaabccaab");

System.out.println("The Regex is: (a*b)");

System.out.println();

while(m.find()) {

System.out.println("Index: " + m.start(1));

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值