Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Java reference

String.matches()

Checks whether the whole string matches a regular expression.

Available since: Java 1.4

Syntax

public boolean matches(String regex)

Parameters

ParameterTypeDescription
regexStringThe regular expression.

Return value

booleantrue if the whole string matches the expression.

Examples

Simple format checks:

void main() {
    IO.println("12345".matches("\\d+"));
    IO.println("12a45".matches("\\d+"));
    IO.println("anna_92".matches("[a-z0-9_]{3,16}"));
    IO.println("+1-555-0100".matches("\\+?[\\d-]+"));
}

Output:

true
false
true
true

The whole string is checked, not a part of it:

void main() {
    IO.println("order 42".matches("\\d+"));
    IO.println("order 42".matches(".*\\d+.*"));
}

Output:

false
true

Notes

s.matches(regex) is short for Pattern.matches(regex, s): every call compiles the expression again. To check many strings, compile a Pattern once. To find a pattern in part of a string, use Matcher.find().

See also

Related recipes

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.