Course contentsShow
← Java
Lesson 2247 of 2,87044. Regular ExpressionsFree lesson

The matches() Method: Full String Match

Using matcher.matches() to test if the entire input string matches the regex pattern.

The matches() Method: Full String Match

You'll learn how to use matcher.matches() to verify that an entire input string conforms to a specific regular expression pattern.

What is Full String Matching?

When you call matches() on a Matcher object, you're asking: "Does my entire input string match this pattern from beginning to end?" This is different from finding a pattern somewhere within the string—matches() enforces that the pattern accounts for every single character in your input.

Think of it like a strict dress code: the entire outfit must match the requirements, not just one accessory. If your pattern is "\\d{3}" (exactly three digits), then "456" matches completely, but "4567" or "ab456" do not—there are extra characters that violate the full-match requirement.

How It Works

After you've compiled a Pattern and created a Matcher, calling matches() returns a boolean:

Pattern pattern = Pattern.compile("\\d{3}");
Matcher matcher = pattern.matcher("456");
boolean result = matcher.matches();  // true - entire string is exactly 3 digits

Matcher matcher2 = pattern.matcher("4567");
boolean result2 = matcher2.matches();  // false - has 4 digits, not 3

Full String vs Partial Matching

The key distinction: matches() implicitly anchors your pattern at both the start and end of the string. If you wanted to find "\\d{3}" anywhere in a longer string, you'd use different methods (which you'll learn later). With matches(), the pattern must describe the complete input from first to last character.

Key Takeaway: Use matcher.matches() when you need to validate that an entire string conforms to a pattern—no extra characters allowed before, after, or anywhere else.