---
title: "Difference between matches() and find() in Java Regex Matcher"
author: "jusi"
date: "2014-12-11T14:21:44Z"
tags: []
categories: ["编程语言"]
slug: "difference-between-matches-and-find-in-java-regex-matcher"
draft: false
lastmod: "2014-12-11T14:22:06Z"
id: 2165159
url: "https://jusi.iteye.com/blog/2165159"
---

I am trying to understand the difference between [`matches()`](http://docs.oracle.com/javase/6/docs/api/java/util/regex/Matcher.html#matches%28%29) and [`find()`](http://docs.oracle.com/javase/6/docs/api/java/util/regex/Matcher.html#find%28%29).

 

[`matches()`](http://docs.oracle.com/javase/6/docs/api/java/util/regex/Matcher.html#matches%28%29) 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
```