Check if string is a prefix of a Javascript RegExp

后端 未结 5 2135
旧巷少年郎
旧巷少年郎 2021-01-04 03:31

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

5条回答
  •  半阙折子戏
    2021-01-04 04:14

    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.

提交回复
热议问题