I’m trying to get the indexes for each pattern that I find in a document. So far I have:
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++;
}
For some reason it keeps finding only the first instance of HelloWorld in temp though which results in an infinite loop. To be honest, I wasn’t sure if you could use matcher.start(current) and matcher.end(current) – it was just a wild guess because matcher.group(current) worked before. This time I need the actual indexes though so matcher.group() wouldn’t work for me.
Modify the regex to look like this: