Difference between matches() and find() in Java Regex

后端 未结 5 1889
感情败类
感情败类 2020-11-21 06:20

I am trying to understand the difference between matches() and find().

According to the Javadoc, (from what I understand), matches() will search the ent

5条回答
  •  灰色年华
    2020-11-21 07:14

    matches tries to match the expression against the entire string and implicitly add a ^ at the start and $ at the end of your pattern, meaning it will not look for a substring. Hence the output of this code:

    public static void main(String[] args) throws ParseException {
        Pattern p = Pattern.compile("\\d\\d\\d");
        Matcher m = p.matcher("a123b");
        System.out.println(m.find());
        System.out.println(m.matches());
    
        p = Pattern.compile("^\\d\\d\\d$");
        m = p.matcher("123");
        System.out.println(m.find());
        System.out.println(m.matches());
    }
    
    /* output:
    true
    false
    true
    true
    */
    

    123 is a substring of a123b so the find() method outputs true. matches() only 'sees' a123b which is not the same as 123 and thus outputs false.

提交回复
热议问题