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

Pattern.matches() Static Convenience Method

Using Pattern.matches(regex, input) for one-time pattern matching without explicitly creating Pattern or Matcher.

Pattern.matches() Static Convenience Method

You'll learn how to perform quick, one-time regex matches without creating separate Pattern or Matcher objects.

The Core Idea

So far, you've been using the full three-step process: compile a Pattern, create a Matcher, and call matches(). But what if you only need to check a pattern once and never reuse it? Java provides Pattern.matches(regex, input) as a shortcut that does all three steps in a single method call.

Think of it like ordering takeout versus cooking at home. The full Pattern/Matcher approach is like stocking your kitchen and cooking—great if you'll make the same dish repeatedly. Pattern.matches() is like ordering delivery—convenient when you just need one quick meal.

How It Works

The static method signature is straightforward:

boolean result = Pattern.matches(regex, input);

Behind the scenes, this method compiles the pattern, creates a matcher, and calls matches() on the full input string. It returns true if the entire string matches the pattern, false otherwise.

Example Usage

// One-time validation: is this a valid 5-digit ZIP code?
boolean isZip = Pattern.matches("\\d{5}", "90210"); // true

// Quick email format check
boolean looksLikeEmail = Pattern.matches("\\w+@\\w+\\.\\w+", "user@example.com"); // true

// These don't match the FULL string
boolean partial = Pattern.matches("Java", "I love Java"); // false (not the entire string)

When to Use It

Use Pattern.matches() for one-off checks where you won't reuse the pattern. If you're validating the same pattern in a loop or multiple times, compile the Pattern once instead—each call to Pattern.matches() recompiles the regex from scratch.

Key Takeaway: Pattern.matches(regex, input) is a convenient static method for one-time full-string pattern matching, but avoid it in performance-critical repeated operations since it recompiles the pattern every time.