user2465439
user2465439

Reputation: 41

non blocking Matcher find

I have a code that is like this:-

Pattern pattern = Pattern.compile("((\\{(.*?)\\}\\{)|(\\{(.*?)\\}$))");
final Matcher matcher = pattern.matcher(str); 
int pos = 0;

while(true)
{
    if(matcher.find(pos))
    {
        ...
        pos--;
    }
    else
        break;
}

What I am seeing is that matcher.find(pos) gets blocked if a pattern match doesnot happen. How to avoid this blocking nature and have it come out if there is no match in the input string.

Upvotes: 0

Views: 249

Answers (2)

Evgeniy Dorofeev
Evgeniy Dorofeev

Reputation: 136002

It does not block but loops infinitely depending on str content. If you find a match at pos = 1 then pos-- returns matcher in the initial state (to pos = 0) and this causes an infinite loop

Upvotes: 1

JBuenoJr
JBuenoJr

Reputation: 975

I'm thinking you are looking for something like this. I'm guessing you are trying to find each pattern in your input string(str). Please see code comments for implementation.

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class PatternTest
{
   public static void main(String[] args)
   {
      String str = "{test1}{test2}{test3}{test4}";

      Pattern pattern = Pattern.compile("((\\{(.*?)\\}\\{)|(\\{(.*?)\\}$))");
      Matcher matcher = pattern.matcher(str);
      int pos = 0;

      while (true)
      {
         if (matcher.find(pos))
         {
            System.out.println("MATCH START: " + matcher.start());
            System.out.println("MATCH END: " + matcher.end());
            System.out.println("MATCH GROUP: " + matcher.group());
            System.out.println();

            // Move position to end of MATCH
            pos = matcher.end()-1;
         }
         else if(matcher.hitEnd())
         {
            // Break when matcher hit end
            break;
         }
         else
         {
            // No Match YET - Move position 1
            System.out.println("NO MATCH");
            pos++;
         }
      }
   }
}

Upvotes: 1

Related Questions