how to use a regex to search backwards effectively?
- by Asaf
hi,
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?
10x, asaf :-)
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 seach 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