Is there an elegant way to do partial regex matches in Java?

java, regex

Solution

Is Matcher.hitEnd() what you're looking for?

Pattern thePattern = Pattern.compile(theRegexString);
Matcher m = thePattern.matcher(theStringToTest);
if (m.matches()) {
    return true;
}
return m.hitEnd();

Problem

What I need is to check whether a given string partially matches a given regex. For example, for the regex `ab[0-9]c`, the strings "a", "ab", "ab3", and "b3c" would "match", but not the strings "d", "abc", or "a3c". What I've been doing is the clunky `a(?:b(?:[0-9](?:c)?)?)?` (which only works for some of the partial matches, specifically those which "begin" to match), but since this is part of an API, I'd rather give the users a more intuitive way of entering their matching regexps. In case the description's not very clear (and I realize it might not be!), this will be used for validating text input on text boxes. I want to prevent any editing that would result in an invalid string, but I can't just match the string against a regular regex, since until it's fully entered, it would not match. For example, using the regex above (`ab[0-9]c`), when I attempt to enter 'a', it's disallowed, since the string "a" does not match the regex. Basically, it's a sort of reverse `startsWith()` which works on regexps. (`new Pattern("ab[0-9]c").startsWith("ab3")` should return `true`.) Any ideas?

Original source