如何使用正则表达式有效地向后搜索? [英] How to use a regex to search backwards effectively?

查看:155
本文介绍了如何使用正则表达式有效地向后搜索?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在搜索带有正则表达式的字符串数组,如下所示:

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.

无论如何,现在我想向后搜索从[line,offset]。

Anyway, now I want to search backwards from that [line,offset].

澄清: 向后我的意思是找到上一场比赛。< br>
例如,假设我在寻找dana

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?" 

并进入第二场比赛。如果我再次 matcher.find(),我将搜索前进并获得第3场比赛。但我想向向后搜索并进入第一场比赛。

上面的代码应输出如下内容:

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的正则表达式引擎无法向后搜索。事实上,我所知道的唯一可以做到这一点的正则表达式引擎是.NET中的那个。

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.

而不是向后搜索,迭代循环中的所有匹配(向前搜索)。如果比赛在您想要的位置之前,请记住它。如果匹配位于您想要的位置之后,请退出循环。在伪代码中(我的Java有点生疏):

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):

storedmatch = ""
while matcher.find {
  if matcher.end < offset {
    storedmatch = matcher.group()
  } else {
    return storedmatch
  }
}

这篇关于如何使用正则表达式有效地向后搜索?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆