Regex Pattern Matching and Extraction
Uses Pattern and Matcher classes to validate email addresses, extract groups, replace text, and split strings with regular expressions.
Code
import java.util.regex.*;
import java.util.List;
public class RegexPatternMatching {
static boolean isValidEmail(String email) {
Pattern pattern = Pattern.compile(
"^[\\w.-]+@[\\w.-]+\\.[a-zA-Z]{2,}$"
);
return pattern.matcher(email).matches();
}
public static void main(String[] args) {
List<String> emails = List.of(
"[email protected]",
"invalid-email",
"[email protected]"
);
for (String email : emails) {
System.out.println(email + " -> " + isValidEmail(email));
}
String text = "Order #12345 confirmed on 2025-01-15";
Pattern orderPattern = Pattern.compile("Order #(\\d+)");
Matcher matcher = orderPattern.matcher(text);
if (matcher.find()) {
System.out.println("Order ID: " + matcher.group(1));
}
String cleaned = text.replaceAll("\\d", "*");
System.out.println("Masked: " + cleaned);
String[] parts = "a,b,,c".split(",");
System.out.println("Parts: " + parts.length);
}
}How it works
Regex Pattern Matching and Extraction keeps everything in the class RegexPatternMatching and the functions isValidEmail and main.
A single loop drives the file — for (String email : emails).
Applying it
Entry signature: static boolean isValidEmail(String email)
Running the file prints labeled results such as Order ID:, Masked:, Parts: — each operation’s effect is visible in the output.
Start the program and main runs isValidEmail one after another.
Statements that matter
return pattern.matcher(email).matches();
Interactive Tools for This Topic
Regular Expression TesterTest regular expressions against sample text with live match highlighting, capture group extraction, and flags support for global, case-insensitive, and multiline modes.JSON to Zod Schema ConverterInfer typed Zod z.object schemas from JSON payloads locally, supporting nested objects, merged array shapes, enums, nullable fields, and JSDoc comments.JSON Schema ValidatorValidate JSON data against a JSON Schema definition and get detailed error reports. Supports type checking, required fields, and common constraint validation.JSONL / NDJSON InspectorValidate NDJSON and JSON Lines line-by-line, pinpoint syntax errors by line number, analyze key frequencies and types, and export a pretty JSON array.
FAQ
- What does Regex Pattern Matching and Extraction print when run?
- Execute the whole file; each printed line is prefixed with a label like `Order ID:`, `Masked:`, `Parts:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.