ITeye博客

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

jusi · 2014-12-11 14:21 · java · 编程语言 · Markdown

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

 

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

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。