How to Use matches() Method in Java String
In Java, use the
matches() method of the String class to check if the entire string matches a given regular expression. It returns true if the string fully matches the pattern, otherwise false.Syntax
The matches() method is called on a String object and takes a single String argument representing a regular expression pattern.
- string.matches(regex): Returns
trueif the entire string matches the regex pattern.
java
boolean result = string.matches("regex");
Example
This example shows how to check if a string contains only digits using matches(). It prints true if the string is all digits, otherwise false.
java
public class MatchesExample { public static void main(String[] args) { String input1 = "12345"; String input2 = "123a5"; boolean isDigits1 = input1.matches("\\d+"); boolean isDigits2 = input2.matches("\\d+"); System.out.println(isDigits1); // true System.out.println(isDigits2); // false } }
Output
true
false
Common Pitfalls
1. matches() checks the entire string: The method returns false if only part of the string matches the pattern. Use Pattern and Matcher classes for partial matches.
2. Escape backslashes: In Java strings, backslashes must be escaped, so use "\\d+" to represent the regex \d+.
3. Case sensitivity: Regex matching is case sensitive by default.
java
/* Wrong: partial match returns false */ "hello123".matches("\\d+"); // false /* Right: full match needed */ "123".matches("\\d+"); // true
Quick Reference
| Method | Description |
|---|---|
| matches(String regex) | Returns true if entire string matches regex pattern |
| Pattern.compile(String regex) | Compiles regex for advanced matching |
| Matcher.find() | Checks for partial matches within string |
Key Takeaways
Use String.matches(regex) to check if the whole string matches a regex pattern.
Remember matches() requires the entire string to match, not just part of it.
Escape backslashes in regex patterns inside Java strings with double backslashes.
For partial matches, use Pattern and Matcher classes instead of matches().