String.matches()
Checks whether the whole string matches a regular expression.
Available since: Java 1.4
Syntax
public boolean matches(String regex)Parameters
| Parameter | Type | Description |
|---|---|---|
| regex | String | The 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
trueThe 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
trueNotes
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
- Matcher.matches() — Checks whether the whole string matches the pattern.
- Pattern.compile() — Compiles a regular expression into a Pattern object that can be reused many times.
- String.replaceAll() — Replaces every match of a regular expression.
- String.contains() — Checks whether a string contains a substring.
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.