In Javascript I have defined a regular expression and now a user is typing in a string. I want to tell him if his string still could match the RegExp if he continues typing
People seem to be splitting evenly on how they interpret this question, so I'll demonstrate the concept with a Java example.
import java.util.regex.*;
public class Test
{
public static void main(String[] args) throws Exception
{
tryMatch("^a*b+$", "a", "ab", "abc");
}
public static void tryMatch(String regex, String... targets)
{
Pattern p = Pattern.compile(regex);
Matcher m = p.matcher("");
System.out.printf("%nregex: %s%n", regex);
System.out.printf("target | matches() | hitEnd()%n");
for (String str : targets)
{
m.reset(str);
System.out.printf("%-6s | %-9B | %-9B%n",
str, m.matches(), m.hitEnd());
}
}
}
output:
regex: ^a*b+$
target | matches() | hitEnd()
a | FALSE | TRUE
ab | TRUE | TRUE
abc | FALSE | FALSE
Target string "a" doesn't match because the regex requires at least one b, but it could be the prefix of a successful match, so hitEnd() returns true. String "ab" has all that's required for a match, but it would also match if we added more b's to the end, so hitEnd() still returns true. With "abc" the match attempt fails before it reaches the end of the target string, so the regex couldn't match any string that starts with "abc".
As far as I know, Javascript doesn't have anything like Java's hitEnd() method, but it might be possible to fake it. If anyone knows how, it'll be that Flagrant Badass, Steven Levithan.