Using matches() for Full String Validation
What you'll learn: How to use matches() to verify that an entire input string conforms to a specific pattern, making it ideal for validation tasks.
The Purpose of matches()
While find() searches for a pattern anywhere within a string, matches() takes a stricter approach—it succeeds only if the entire input string matches the pattern from start to finish. This makes it perfect for validation scenarios where you need to ensure the whole input conforms to specific rules.
Think of it like a security checkpoint: find() asks "Is this item somewhere in your bag?", while matches() asks "Does your entire bag contain only approved items?"
How matches() Works
When you call matcher.matches(), the regex engine attempts to match the pattern against the complete string. There's no partial matching—either the entire string fits the pattern or it doesn't.
Pattern pattern = Pattern.compile("\\d{3}-\\d{2}-\\d{4}");
Matcher matcher = pattern.matcher("123-45-6789");
boolean isValid = matcher.matches(); // true - entire string matches
matcher.reset("123-45-6789-extra");
boolean stillValid = matcher.matches(); // false - extra characters
Common Validation Use Cases
The matches() method excels at:
- Email validation: Ensuring input looks like a complete email address
- Phone number formats: Verifying the entire string matches your expected pattern
- Postal codes: Checking that input is exactly the right format
- Username requirements: Confirming input meets length and character rules
Pattern usernamePattern = Pattern.compile("[a-zA-Z][a-zA-Z0-9_]{4,14}");
boolean validUsername = usernamePattern.matcher("user_123").matches(); // true
boolean invalid = usernamePattern.matcher("123user").matches(); // false - starts with digit
Key Takeaway: Use matches() when you need to validate that the entire input string conforms to your pattern—no more, no less—making it the go-to method for input validation tasks.