Regular Expressions
IntermediateJava's java.util.regex package provides compiled patterns and matchers for searching, extracting, and replacing text with regular expressions.
Overview
Regular expressions in Java are handled through Pattern (compiled regex) and Matcher (engine that applies the pattern to input). Because compilation is expensive, patterns should be compiled once and reused. String convenience methods like matches(), replaceAll(), split() delegate to Pattern internally. Understanding groups, lookaheads, and flags is essential for advanced text processing.
Pattern and Matcher Basics
Compile a pattern once (static final is common) then reuse it. Matcher.find() searches for the next match; matches() checks the whole input. Groups are captured with parentheses and retrieved with group(n).
import java.util.regex.*;
// Compile once — expensive operation
private static final Pattern EMAIL =
Pattern.compile("^[\\w.+-]+@[\\w-]+\\.[\\w.]+$");
public boolean isValidEmail(String email) {
return EMAIL.matcher(email).matches();
}
// Extract groups
Pattern date = Pattern.compile("(\\d{4})-(\\d{2})-(\\d{2})");
Matcher m = date.matcher("Today is 2025-06-15 and tomorrow is 2025-06-16");
while (m.find()) {
System.out.println("Year=" + m.group(1)
+ " Month=" + m.group(2)
+ " Day=" + m.group(3));
}String Convenience Methods
String provides regex-powered methods: matches(regex), replaceAll(regex, replacement), replaceFirst(regex, replacement), split(regex).
Note: these compile the pattern on every call — for repeated use, prefer a cached Pattern.
String text = "Hello World Java";
// Split on one or more whitespace
String[] words = text.split("\\s+");
// ["Hello", "World", "Java"]
// Replace all digits with #
String masked = "Phone: 123-456-7890"
.replaceAll("\\d", "#");
// "Phone: ###-###-####"
// Named groups (Java 7+)
Pattern p = Pattern.compile(
"(?<year>\\d{4})-(?<month>\\d{2})-(?<day>\\d{2})");
Matcher m = p.matcher("2025-06-15");
if (m.matches()) {
System.out.println(m.group("year")); // "2025"
}Flags and Common Patterns
Pattern flags modify matching behaviour. Common flags: CASE_INSENSITIVE ((?i)), MULTILINE (^ and $ match line boundaries), DOTALL (. matches newlines), COMMENTS (whitespace and # comments allowed in pattern).
Flags can be embedded in the pattern with (?flag) or passed to Pattern.compile(regex, flags).
// Case-insensitive
Pattern ci = Pattern.compile("hello", Pattern.CASE_INSENSITIVE);
ci.matcher("HELLO World").find(); // true
// Multi-line — ^ and $ match line starts/ends
Pattern ml = Pattern.compile("^\\w+", Pattern.MULTILINE);
// Common patterns reference
String ipPattern = "\\b(?:\\d{1,3}\\.){3}\\d{1,3}\\b";
String urlPattern = "https?://[\\w./%-]+";
String phonePattern = "\\+?[\\d\\s()-]{7,15}";
String hexPattern = "#[0-9A-Fa-f]{3,6}";Key Points to Remember
- Compile patterns once with Pattern.compile() — compilation is expensive.
- Matcher.find() searches; matches() checks the entire input string.
- Groups: (expr) captures, (?<name>expr) names them, group(n) or group("name") retrieves.
- String.matches/replaceAll/split recompile on each call — use cached Pattern for loops.
- Flags like CASE_INSENSITIVE, MULTILINE, DOTALL modify matching semantics.
Practice Regular Expressions in the Playground
Run and modify code directly in your browser - no setup needed.
Interview Questions
Sign in to ask AriaWhy should Pattern be stored as a static final field?
What is the difference between Matcher.find() and Matcher.matches()?
How do named capturing groups work in Java regex?
What does the DOTALL flag do and when would you use it?
How would you write a regex to validate an email address?
Ask Aria about Regular Expressions
Your personal AI tutor — ask anything about this concept