A Regular Expression (Regex) is an expressive sequence of characters defining a search pattern. In Java, the java.util.regex package provides high-performance pattern compilation and string parsing used universally for email verification, phone formatting, web scraping, and log parsing.
Pattern.compile("regex"). Immutable and thread-safe.pattern.matcher(input). Not thread-safe.| Construct | Syntax | Matches |
|---|---|---|
| Digit | \d | Any digit from [0-9] |
| Non-Digit | \D | Any character that is NOT a digit |
| Whitespace | \s | Spaces, tabs (\t), newlines (\n) |
| Word Character | \w | Alphanumeric plus underscore: [a-zA-Z_0-9] |
| Boundaries | ^ and $ | Start of line (^) and End of line ($) |
| Quantifiers | ?, *, + | 0 or 1 time (?), 0 or more (*), 1 or more (+) |
| Exact Count | {n}, {n,m} | Exactly n times, or between n and m times |
import java.util.regex.Pattern;
import java.util.regex.Matcher;
public class EmailValidator {
// RFC 5322 compliant practical regex pattern
private static final String EMAIL_REGEX = "^[a-zA-Z0-9_+&*-]+(?:\.[a-zA-Z0-9_+&*-]+)*@(?:[a-zA-Z0-9-]+\.)+[a-zA-Z]{2,7}$";
private static final Pattern PATTERN = Pattern.compile(EMAIL_REGEX);
public static boolean isValidEmail(String email) {
if (email == null) return false;
return PATTERN.matcher(email).matches();
}
public static void main(String[] args) {
String[] testEmails = {
"aarav.sharma@veewom.com",
"student_101@college.edu.in",
"invalid-email@",
"bad..dots@gmail.com"
};
for (String email : testEmails) {
System.out.printf("%-30s : %s%n", email, isValidEmail(email) ? "VALID" : "INVALID");
}
}
}
Parentheses () group sub-patterns and allow targeted value extraction via matcher.group(index):
import java.util.regex.Pattern;
import java.util.regex.Matcher;
public class LogParser {
public static void main(String[] args) {
String logLine = "2026-11-05 21:05:32 [ERROR] User 10492: Connection timed out on port 3306";
// Regex with 3 capturing groups: Timestamp, LogLevel, Message
String regex = "^(\\d{4}-\\d{2}-\\d{2} \\d{2}:\\d{2}:\\d{2}) \\[([A-Z]+)\\] (.*)$";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(logLine);
if (matcher.find()) {
System.out.println("Timestamp: " + matcher.group(1));
System.out.println("Severity: " + matcher.group(2));
System.out.println("Details: " + matcher.group(3));
}
}
}
Timestamp: 2026-11-05 21:05:32 Severity: ERROR Details: User 10492: Connection timed out on port 3306
Never call str.matches("regex") inside high-throughput loops. Each invocation re-compiles the regex pattern from scratch. Always declare private static final Pattern PATTERN = Pattern.compile("...") once and reuse the instance.
.*): Reads the entire input first, then backtracks one character at a time until a match is found..*?): Matches as few characters as possible from the start, consuming more only if needed..*+): Reads greedily and never backtracks, preventing catastrophic backtracking performance crashes.Accelerate your Java mastery by studying these tightly connected core tutorials:
String.matches() and String.replaceAll().
Interpreter and Template patterns.
Tokenizing file streams with regex.
Tricky output tracing and code drills.