Java Pattern matches() Method
Example
Check if a whole text contains only digits:
import java.util.regex.Pattern;
public class Main {
public static void main(String[] args) {
System.out.println(Pattern.matches("[0-9]+", "12345"));
System.out.println(Pattern.matches("[0-9]+", "12 apples"));
}
}
Definition and Usage
The matches() method checks if a whole text matches a regular expression.
It is a static method, so you do not need to create a Pattern object first. In the example, [0-9]+ means "one or more digits from 0 to 9". The text "12 apples" also has a space and letters, so it does not match.
Tip: If you check many texts with the same pattern, compile the pattern once with compile(), and then use the matches() method of a Matcher.
Syntax
public static boolean matches(String regex, CharSequence input)
Parameter Values
| Parameter | Description |
|---|---|
| regex | Required. The regular expression. |
| input | Required. The text to check. |
Technical Details
| Returns: | true if the whole text matches the regular expression, otherwise false. |
|---|---|
| Throws: | PatternSyntaxException - if the regular expression is not valid. |
Related Pages
❮ RegEx Methods