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
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…