How to use a regex to search backwards effectively?

后端 未结 5 963
温柔的废话
温柔的废话 2020-12-18 22:51

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].         


        
5条回答
  •  旧时难觅i
    2020-12-18 23:24

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

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

提交回复
热议问题