javaintermediate
Java Regex — Pattern Matching Examples
Common regex patterns with Pattern and Matcher: email, URL, phone, extraction, and replacement.
javaPress ⌘/Ctrl + Shift + C to copy
import java.util.regex.*;
import java.util.List;
import java.util.stream.Collectors;
public class RegexDemo {
// Compiled patterns (reuse for performance)
static final Pattern EMAIL = Pattern.compile(
"^[\\w.+-]+@[\\w-]+\\.[\\w.]+$");
static final Pattern URL = Pattern.compile(
"https?://[\\w.-]+(?:/[\\w./-]*)?");
static final Pattern PHONE = Pattern.compile(
"\\+?\\d{1,4}[-.\\s]?\\(?\\d{1,3}\\)?[-.\\s]?\\d{3,4}[-.\\s]?\\d{4}");
// Validate
static boolean isValidEmail(String email) {
return EMAIL.matcher(email).matches();
}
// Extract all matches
static List<String> extractUrls(String text) {
return URL.matcher(text).results()
.map(MatchResult::group)
.toList();
}
// Named groups
static void parseLog() {
Pattern logPattern = Pattern.compile(
"\\[(?<timestamp>[^]]+)] (?<level>\\w+) (?<message>.+)");
String log = "[2024-01-15 10:30:00] ERROR Database connection failed";
Matcher m = logPattern.matcher(log);
if (m.matches()) {
System.out.println("Time: " + m.group("timestamp"));
System.out.println("Level: " + m.group("level"));
System.out.println("Msg: " + m.group("message"));
}
}
// Replace with transform
static String maskEmails(String text) {
return EMAIL.matcher(text).replaceAll(mr -> {
String email = mr.group();
int atIdx = email.indexOf('@');
return email.charAt(0) + "***" + email.substring(atIdx);
});
}
// Split with regex
static String[] tokenize(String csv) {
return csv.split(",\\s*");
}
public static void main(String[] args) {
System.out.println(isValidEmail("alice@test.com")); // true
System.out.println(isValidEmail("invalid@")); // false
String text = "Visit https://example.com and http://test.org/page";
System.out.println(extractUrls(text));
parseLog();
}
}Use Cases
- Input validation for emails, URLs, and phone numbers
- Log file parsing with named capture groups
- Text extraction and transformation
Tags
Related Snippets
Similar patterns you can reuse in the same workflow.
kotlinbeginner
Kotlin Regex Pattern Matching
Use Kotlin regex for validation, extraction, replacing, and destructuring with named groups.
Best for: Input validation for forms and APIs
#kotlin#regex
javaintermediate
Spring Boot — Custom Validator Annotation
Create custom validation annotations with ConstraintValidator for domain-specific field validation.
Best for: Domain-specific input validation
#spring-boot#validation
kotlinintermediate
Regex — Match, Replace, and Extract
Use Kotlin regex for pattern matching: find, replace, named groups, and structured extraction.
Best for: Log file parsing and analysis
#kotlin#regex
javabeginner
Reverse a String in Java
Multiple ways to reverse a string in Java including StringBuilder, char array, and stream approaches.
Best for: String manipulation in coding interviews
#java#string