gpt4 book ai didi

java - 匹配器查找第 n 个匹配索引

转载 作者:行者123 更新时间:2023-12-01 07:34:11 26 4
gpt4 key购买 nike

我正在尝试获取在文档中找到的每个模式的索引。到目前为止我已经:

    String temp = "This is a test to see HelloWorld in a test that sees HelloWorld in a test";
Pattern pattern = Pattern.compile("HelloWorld");
Matcher matcher = pattern.matcher(temp);
int current = 0;
int start;
int end;

while (matcher.find()) {
start = matcher.start(current);
end = matcher.end(current);
System.out.println(temp.substring(start, end));
current++;
}

出于某种原因它始终只在temp中查找HelloWorld的第一个实例,但这会导致无限循环。老实说,我不确定您是否可以使用 matcher.start(current)matcher.end(current) - 这只是一个疯狂的猜测,因为 matcher.group(current) 之前工作过。这次我需要实际的索引,所以 matcher.group() 对我来说不起作用。

最佳答案

修改正则表达式,如下所示:

while (matcher.find()) {
start = matcher.start();
end = matcher.end();
System.out.println(temp.substring(start, end));
}

关于java - 匹配器查找第 n 个匹配索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14253464/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com