I’m searching forward in an array of strings with a regex, like this:
for (int j = line; j < lines.length; j++) {
if (lines[j] == null || lines[j].isEmpty()) {
continue;
}
matcher = pattern.matcher(lines[j]);
if (matcher.find(offset)) {
offset = matcher.end();
line = j;
System.out.println("found \""+matcher.group()+"\" at line "+line+" ["+matcher.start()+","+offset+"]");
return true;
}
offset = 0;
}
return false;
Note that in my implementation above I save the line and offset for continuous searches.
Anyway, now I want to search backwards from that [line,offset].
My question: is there a way to search backwards with a regex efficiently? if not, what could be an alternative?
Clarification: By backwards I mean finding the previous match.
For example, say that I’m searching for “dana” in
"dana nama? dana kama! lama dana kama?"
and got to the 2nd match. If I do matcher.find() again, I’ll search forward and get the 3rd match. But I want to search backwards and get to the 1st match.
the code above should then output something like:
found "dana" at line 0 [0,3] // fwd
found "dana" at line 0 [11,14] // fwd
found "dana" at line 0 [0,3] // bwd
Java’s regular expression engine cannot search backwards. In fact, the only regex engine that I know that can do that is the one in .NET.
Instead of searching backwards, iterate over all the matches in a loop (searching forward). If the match is prior to the position you want, remember it. If the match is after the position you want, exit from the loop. In pseudo code (my Java is a little rusty):