How can I perform a partial match with java.util.regex.*?

后端 未结 7 1488
野的像风
野的像风 2020-11-30 03:16

I have been using the java.util.regex.* classes for Regular Expression in Java and all good so far. But today I have a different requirement. For example consider the patter

7条回答
  •  Happy的楠姐
    2020-11-30 04:04

    You should have looked more closely at the Matcher API; the hitEnd() method works exactly as you described:

    import java.util.regex.*;
    
    public class Test
    {
      public static void main(String[] args) throws Exception
      {
        String[] ss = { "aabb", "aa", "cc", "aac" };
        Pattern p = Pattern.compile("aabb");
        Matcher m = p.matcher("");
    
        for (String s : ss) {
          m.reset(s);
          if (m.matches()) {
            System.out.printf("%-4s : match%n", s);
          }
          else if (m.hitEnd()) {
            System.out.printf("%-4s : partial match%n", s);
          }
          else {
            System.out.printf("%-4s : no match%n", s);
          }
        }
      }
    }
    

    output:

    aabb : match
    aa   : partial match
    cc   : no match
    aac  : no match
    

    As far as I know, Java is the only language that exposes this functionality. There's also the requireEnd() method, which tells you if more input could turn a match into a non-match, but I don't think it's relevant in your case.

    Both methods were added to support the Scanner class, so it can apply regexes to a stream without requiring the whole stream to be read into memory.

提交回复
热议问题