Can java.util.regex.Pattern do partial matches?
Actually, you are in luck: Java's regex does have the method you want:
public boolean hitEnd()
Returns true if the end of input was hit by the search engine in the last match operation performed by this matcher.
When this method returns true, then it is possible that more input would have changed the result of the last search.
So in your case:
String input="AA";
Pattern pat=Pattern.compile("AAB");
Matcher matcher=pat.matcher(input);
System.out.println(matcher.matches()); // prints "false"
System.out.println(matcher.hitEnd()); // prints "true"
An alternative to hitEnd is to specify the requirement in the RE itself.
// Accepts up to 5 'A's or 5 'A's and a 'B' (and anything following)
Pattern pat = Pattern.compile("^(?:A{1,5}$|A{5}B)");
boolean yes = pat.matcher("AA").find();
boolean no = pat.matcher("BB").find();
Yes, Java provides a way to do that. First you have to call one of the standard methods to apply the regex, like matches()
or find()
. If that returns false
, you can use the hitEnd()
method to find out if some longer string could have matched:
String[] inputs = { "AA", "BB" };
Pattern p = Pattern.compile("AAAAAB");
Matcher m = p.matcher("");
for (String s : inputs)
{
m.reset(s);
System.out.printf("%s -- full match: %B; partial match: %B%n",
s, m.matches(), m.hitEnd());
}
output:
AA -- full match: FALSE; partial match: TRUE
BB -- full match: FALSE; partial match: FALSE