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

后端 未结 5 1880
感情败类
感情败类 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:18

    find() will consider the sub-string against the regular expression where as matches() will consider complete expression.

    find() will returns true only if the sub-string of the expression matches the pattern.

    public static void main(String[] args) {
            Pattern p = Pattern.compile("\\d");
            String candidate = "Java123";
            Matcher m = p.matcher(candidate);
    
            if (m != null){
                System.out.println(m.find());//true
                System.out.println(m.matches());//false
            }
        }
    

提交回复
热议问题