Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Java reference

Matcher.matches()

Checks whether the whole string matches the pattern.

Available since: Java 1.4

Syntax

public boolean matches()

Return value

booleantrue if the entire string matches the pattern.

Examples

matches() versus find():

void main() {
    Pattern p = Pattern.compile("\\d+");
    IO.println(p.matcher("123").matches());
    IO.println(p.matcher("abc123").matches());
    IO.println(p.matcher("abc123").find());
}

Output:

true
false
true

Validating and parsing a time in one step:

void main() {
    Matcher m = Pattern.compile("(\\d{1,2}):(\\d{2})").matcher("9:45");
    if (m.matches()) {
        int minutes = Integer.parseInt(m.group(1)) * 60 + Integer.parseInt(m.group(2));
        IO.println(minutes);
    }
}

Output:

585

Notes

^ and $ are not needed with matches() — the whole string is checked. There is also the in-between lookingAt(): the match must start at the beginning of the string but need not reach the end.

See also

  • String.matches() — Checks whether the whole string matches a regular expression.
  • Matcher.find() — Searches for the next match of the pattern anywhere in the string.
  • Matcher.group() — Returns the text of the current match or of one of its parenthesized groups.

In the tutorial

  • Regular expressions — Regular expressions in Java: matches, replaceAll, splitting by a pattern, the Pattern and Matcher classes, groups and escaping backslashes.

Thanks for reading!

Donate to the site — we work hard for you.