How can I perform a partial match with java.util.regex.*?

java, regex

Solution

You should have looked more closely at the Matcher API; the `hitEnd()` method works exactly as you described:

import java.util.regex.*;

public class Test
{
  public static void main(String[] args) throws Exception
  {
    String[] ss = { "aabb", "aa", "cc", "aac" };
    Pattern p = Pattern.compile("aabb");
    Matcher m = p.matcher("");

    for (String s : ss) {
      m.reset(s);
      if (m.matches()) {
        System.out.printf("%-4s : match%n", s);
      }
      else if (m.hitEnd()) {
        System.out.printf("%-4s : partial match%n", s);
      }
      else {
        System.out.printf("%-4s : no match%n", s);
      }
    }
  }
}

output:

aabb : match
aa   : partial match
cc   : no match
aac  : no match

As far as I know, Java is the only language that exposes this functionality. There's also the `requireEnd()` method, which tells you if more input could turn a match into a non-match, but I don't think it's relevant in your case.

Both methods were added to support the Scanner class, so it can apply regexes to a stream without requiring the whole stream to be read into memory.

Problem

I have been using the java.util.regex.* classes for Regular Expression in Java and all good so far. But today I have a different requirement. For example consider the pattern to be "aabb". Now if the input String is aa it will definitely not match, however there is still possibility that if I append bb it becomes aabb and it matches. However if I would have started with cc, no matter what I append it will never match. I have explored the Pattern and Matcher class but didn't find any way of achieving this. The input will come from user and system have to wait till pattern matches or it will never match irrespective of any input further. Any clue? Thanks.

Original source