Java
Regular Expressions
Pattern and Matcher.
By EZ4Code Team
regexregex
Code
import java.util.regex.*;
String text = "Phone: 138-1234-5678, Email: [email protected]";
// Find
Pattern phonePattern = Pattern.compile("\d{3}-\d{4}-\d{4}");
Matcher matcher = phonePattern.matcher(text);
if (matcher.find()) {
System.out.println("Phone: " + matcher.group());
}
// Replace
String result = text.replaceAll("\d", "*");
// Split
String[] parts = "a,b,,c".split(",");
// Validate
boolean isValid = "[email protected]".matches(
"[\w.]+@[\w.]+\.\w+");
// Named capture group
Pattern p = Pattern.compile("(?<year>\d{4})-(?<month>\d{2})");
Matcher m = p.matcher("2024-01");
if (m.find()) {
System.out.println(m.group("year"));
System.out.println(m.group("month"));
}Explanation
Pattern compiles regex; Matcher performs matching, searching, and replacement.
More Java Snippets
String Operations and StringBuilder
Manipulate strings with split, join, substring, and StringBuilder in Java.
Stream API
Process collections using the Stream API.
Lambda Expressions
Simplify code with Lambda expressions.
Optional
Handle null values elegantly.
Collection Operations
Common operations on List, Set, and Map.
Exception Handling
try-catch-finally and custom exceptions.