Java 匹配器查找第n个匹配索引
我试图为我在文档中找到的每个模式获取索引。到目前为止,我已经:Java 匹配器查找第n个匹配索引,java,regex,pattern-matching,Java,Regex,Pattern Matching,我试图为我在文档中找到的每个模式获取索引。到目前为止,我已经: 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;
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));
}
问题在于这行代码
start = matcher.start(current);
current
在第一次迭代后为1。不要将索引传递给start(int)
和end(int)
。API声明该参数是组号。在您的情况下,只有零是正确的。改用start()
和end()
匹配器将在每次迭代中移动到下一个匹配,因为您调用了:
此方法从输入序列的开头开始,或者,如果方法的上一次调用成功且匹配器此后未重置,则从上一次匹配未匹配的第一个字符开始
如果您只需要匹配文本的起始偏移量和结束偏移量,而不需要当前组,则可以:
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;
while (matcher.find()) {
System.out.println(temp.substring(matcher.start(), matcher.end()));
}
我会做你想做的
String temp = "This is a test to see HelloWorld in a test that sees HelloWorld in a test";
Pattern pattern = Pattern.compile("HelloWorld");
Matcher m = pattern.matcher(temp);
while (matcher.find()) {
System.out.println(temp.substring(m.start(), m.stop()));
}
String temp = "This is a test to see HelloWorld in a test that sees HelloWorld in a test";
Pattern pattern = Pattern.compile("HelloWorld");
Matcher m = pattern.matcher(temp);
while (matcher.find()) {
System.out.println(temp.substring(m.start(), m.stop()));
}