Can java.util.regex.Pattern do partial matches?

后端 未结 5 1647
时光取名叫无心
时光取名叫无心 2020-12-01 18:58

Is it possible to know if a stream/string contains an input that could match a regular expression.

For example

 String input=\"AA\";         


        
5条回答
  •  抹茶落季
    2020-12-01 19:40

    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"
    

提交回复
热议问题