How to use a regex to search backwards effectively?

后端 未结 5 948
温柔的废话
温柔的废话 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条回答
  •  借酒劲吻你
    2020-12-18 23:22

    I use the following simple class to search backwards in java

    public class ReverseMatcher {
       private final Matcher _matcher;
       private final Stack _results = new Stack<>();
    
       public ReverseMatcher(Matcher matcher){
           _matcher = matcher;
       }
    
       public boolean find(){
           return find(_matcher.regionEnd());
       }
    
       public boolean find(int start){
           if (_results.size() > 0){
               _results.pop();
               return _results.size() > 0;
           }
           boolean res = false;
           while (_matcher.find()){            
               if (_matcher.end() > start)
                   break;
               res = true;
               _results.push(_matcher.toMatchResult());
           }
           return res;
       }
    
       public String group(int group){
           return _results.peek().group(group);               
       }
    
       public String group(){
           return _results.peek().group();               
       }
    
       public int start(){
           return _results.peek().start();
       }    
    
       public int end(){
           return _results.peek().end();
       }
    }
    

    using:

    String srcString = "1 2 3 4 5 6 7 8 9";
    String pattern = "\\b[0-9]*\\b";
    Pattern p = Pattern.compile(pattern);
    Matcher m = p.matcher(srcString);
    ReverseMatcher rm = new ReverseMatcher(m);
    while (rm.find())
       System.out.print(rm.group() + " ");
    

    output: 9 8 7 6 5 4 3 2 1

    or

    while (rm.find(9))
       System.out.print(rm.group() + " ");
    

    output: 5 4 3 2 1

提交回复
热议问题