Java 中的 MatchResult start() 方法示例。
javaobject oriented programmingprogramming更新于 2025/2/8 23:08:17
java.util.regex.MatcheResult 接口提供了检索匹配结果的方法。
您可以使用 Matcher 类的 toMatchResult() 方法获取此接口的对象。此方法返回表示当前匹配器匹配状态的 MatchResult 对象。
此接口的 start() 方法返回当前匹配的起始索引。
示例
import java.util.Scanner;
import java.util.regex.MatchResult;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class StartExample {
public static void main(String args[]) {
//从用户读取字符串
System.out.println("输入字符串");
Scanner sc = new Scanner(System.in);
String input = sc.nextLine();
String regex = "\W";
//编译正则表达式
Pattern pattern = Pattern.compile(regex);
//检索匹配器对象
Matcher matcher = pattern.matcher(input);
if(matcher.find()) {
System.out.println("匹配发生");
}else {
System.out.println("未发生匹配");
}
//检索 MatchResult 对象
MatchResult res = matcher.toMatchResult();
int start = res.start();
System.out.println(start);
}
}
输出
输入字符串 此 * 为 # 示例 % 文本,其中 & 为非单词字符 匹配次数 4
相关文章
有用资源
java 参考教程 - 该教程包含有关 java 的更多信息:https://www.cainiaomax.com/java/

