Regular Expressions with Pattern and Matcher
Validate emails, extract substrings, and replace patterns using Java regex.
Regular Expressions with Pattern and Matcher
Java's java.util.regex package provides Pattern and Matcher for powerful text matching, validation, extraction, and replacement.
Why Regular Expressions?
Regular expressions (regex) are patterns for matching text. In Java, they are used for validating emails, phone numbers, extracting data from logs, and parsing structured text.
import java.util.regex.*;
// Is this a valid email?
String email = "alice@example.com";
boolean valid = email.matches("[a-zA-Z0-9._%+\\-]+@[a-zA-Z0-9.\\-]+\\.[a-zA-Z]{2,}");
System.out.println(valid); // true
// Extract version numbers from a string
String log = "App v1.2.3 deployed; api v2.0.0 started";
Pattern p = Pattern.compile("v(\\d+\\.\\d+\\.\\d+)");
Matcher m = p.matcher(log);
while (m.find()) System.out.println(m.group(1));
// 1.2.3
// 2.0.0All lessons in this course
- String Immutability and the String Pool
- StringBuilder for Efficient Concatenation
- Text Blocks and String.format
- Regular Expressions with Pattern and Matcher