Check if a String matches specific regular expression
Categories:
Mastering Regular Expressions: How to Check if a String Matches a Pattern in Java

Learn the fundamentals of using regular expressions in Java to validate string formats, search for patterns, and ensure data integrity.
Regular expressions (regex) are powerful tools for pattern matching within strings. In Java, the java.util.regex
package provides classes like Pattern
and Matcher
to work with regex. This article will guide you through the process of checking if a string conforms to a specific regular expression, covering common use cases and best practices.
Understanding Java's Regex API
Java's regex API is built around two core classes: Pattern
and Matcher
. The Pattern
class represents a compiled regular expression. Once compiled, a Pattern
object can be used to create Matcher
objects, which perform match operations against an input string. This separation allows for efficient reuse of compiled patterns, especially when performing multiple matches with the same regex.
flowchart TD A[Input String] --> B{Compile Regex Pattern} B --> C[Create Matcher Object] C --> D{Perform Match Operation} D -- Match Found --> E[True] D -- No Match --> F[False]
Basic workflow for regex matching in Java
Basic String Matching with matches()
For simple, one-off checks where you need to determine if an entire string matches a given regular expression, the String.matches()
method is often the most convenient. This method internally compiles the regex and creates a matcher, then checks if the entire string matches the pattern. It's a shortcut for Pattern.compile(regex).matcher(inputString).matches()
.
public class RegexExample {
public static void main(String[] args) {
String email = "test@example.com";
String invalidEmail = "invalid-email";
String phoneNumber = "123-456-7890";
// Regex for a simple email pattern
String emailRegex = "^[A-Za-z0-9+_.-]+@(.+)$";
// Regex for a phone number (e.g., XXX-XXX-XXXX)
String phoneRegex = "^\\d{3}-\\d{3}-\\d{4}$";
System.out.println("Email '" + email + "' matches: " + email.matches(emailRegex));
System.out.println("Email '" + invalidEmail + "' matches: " + invalidEmail.matches(emailRegex));
System.out.println("Phone number '" + phoneNumber + "' matches: " + phoneNumber.matches(phoneRegex));
}
}
Using String.matches()
for quick regex checks.
String.matches()
method checks if the entire string matches the pattern. If you need to find a pattern within a larger string, you'll need to use Pattern
and Matcher
directly.Advanced Matching with Pattern
and Matcher
When you need more control, better performance for repeated matches, or to extract specific parts of a match, using Pattern
and Matcher
explicitly is the way to go. This approach involves three steps:
- Compile the Pattern: Create a
Pattern
object from your regex string. - Create a Matcher: Obtain a
Matcher
object by callingpattern.matcher(inputString)
. - Perform Match Operations: Use methods like
matcher.matches()
,matcher.find()
,matcher.lookingAt()
to check for matches.
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class AdvancedRegexExample {
public static void main(String[] args) {
String logEntry = "ERROR: User 'john.doe' failed login at 2023-10-27 10:30:00";
String anotherLogEntry = "INFO: Application started successfully.";
// Regex to find 'ERROR' messages and capture the username
String errorRegex = ".*ERROR: User '([a-zA-Z0-9.]+)' failed login.*";
// 1. Compile the Pattern
Pattern pattern = Pattern.compile(errorRegex);
// 2. Create a Matcher for the first log entry
Matcher matcher1 = pattern.matcher(logEntry);
// 3. Perform Match Operations
if (matcher1.matches()) {
System.out.println("Log entry 1 contains an ERROR.");
// Access captured groups (username in this case)
System.out.println("Failed login user: " + matcher1.group(1));
} else {
System.out.println("Log entry 1 does not match the ERROR pattern.");
}
// Create another Matcher for the second log entry
Matcher matcher2 = pattern.matcher(anotherLogEntry);
if (matcher2.matches()) {
System.out.println("Log entry 2 contains an ERROR.");
} else {
System.out.println("Log entry 2 does not match the ERROR pattern.");
}
// Example using find() to locate patterns within a larger text
String text = "The quick brown fox jumps over the lazy dog. Fox is a common animal.";
Pattern wordPattern = Pattern.compile("fox", Pattern.CASE_INSENSITIVE);
Matcher wordMatcher = wordPattern.matcher(text);
while (wordMatcher.find()) {
System.out.println("Found 'fox' at index: " + wordMatcher.start() + " to " + wordMatcher.end());
}
}
}
Using Pattern
and Matcher
for more flexible and efficient regex operations, including group capturing.
Pattern
is a relatively expensive operation. If you're using the same regex multiple times, compile it once and reuse the Pattern
object rather than recompiling it every time.