Regular Expressions with Pattern and Matcher
Validate emails, extract substrings, and replace patterns using Java regex.
Regular Expressions with Pattern and Matcher is a free Java Academy lesson on CoddyKit — lesson 4 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Java Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.
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.0Regex Syntax Basics
Key regex metacharacters:
.— any character\d— digit;\w— word char;\s— whitespace*— 0+;+— 1+;?— 0 or 1{n,m}— between n and m times^/$— start/end of line[abc]— character class
// In Java strings, backslash must be doubled: \d = "\\d"
Pattern digit = Pattern.compile("\\d+"); // one or more digits
Pattern word = Pattern.compile("\\w{3,20}"); // 3-20 word chars
Pattern space = Pattern.compile("\\s+"); // whitespace
Pattern phone = Pattern.compile("\\d{3}-\\d{3}-\\d{4}"); // 555-867-5309
System.out.println(digit.matcher("42").matches()); // true
System.out.println(phone.matcher("555-867-5309").matches()); // truePattern.compile and Matcher
Compile a pattern once and reuse the Matcher for multiple inputs — more efficient than using String.matches() for repeated validation.
import java.util.regex.*;
Pattern emailPattern = Pattern.compile(
"^[a-zA-Z0-9._%+\\-]+@[a-zA-Z0-9.\\-]+\\.[a-zA-Z]{2,6}$"
);
String[] emails = {"alice@example.com", "bad@", "test.user@co.uk", "no-at-sign"};
for (String e : emails) {
Matcher m = emailPattern.matcher(e);
System.out.println(e + " -> " + (m.matches() ? "valid" : "invalid"));
}find() vs matches()
matches() tests the entire string. find() finds the next occurrence within the string. Use find for searching, matches for full validation.
import java.util.regex.*;
Pattern price = Pattern.compile("\\d+\\.\\d{2}");
String invoice = "Total: 129.99, Tax: 10.40, Shipping: 5.00";
Matcher m = invoice.matcher(invoice);
// find() locates all matches
while (m.find()) {
System.out.println("Found: " + m.group() + " at " + m.start());
}
// Found: 129.99 at 7
// Found: 10.40 at 20
// Found: 5.00 at 34Capture Groups
Parentheses create capture groups. Use group(n) to extract matched substrings.
import java.util.regex.*;
Pattern date = Pattern.compile("(\\d{4})-(\\d{2})-(\\d{2})");
Matcher m = date.matcher("Deployed on 2024-06-15 and 2024-07-01");
while (m.find()) {
String year = m.group(1);
String month = m.group(2);
String day = m.group(3);
System.out.println(year + "/" + month + "/" + day);
}
// 2024/06/15
// 2024/07/01Named Groups
Named groups (?<name>...) make capture groups more readable and accessible by name.
import java.util.regex.*;
Pattern log = Pattern.compile(
"(?<timestamp>\\d{4}-\\d{2}-\\d{2}) (?<level>[A-Z]+) (?<message>.+)"
);
String line = "2024-06-15 ERROR Database connection failed";
Matcher m = log.matcher(line);
if (m.matches()) {
System.out.println("Time: " + m.group("timestamp"));
System.out.println("Level: " + m.group("level"));
System.out.println("Message: " + m.group("message"));
}
// Time: 2024-06-15
// Level: ERROR
// Message: Database connection failedreplaceAll and replaceFirst
Pattern-based replacement: replace all occurrences or just the first.
import java.util.regex.*;
String text = "Call us at 123-456-7890 or 098-765-4321";
// Mask phone numbers for privacy logs
String masked = text.replaceAll("\\d{3}-\\d{3}-\\d{4}", "XXX-XXX-XXXX");
System.out.println(masked);
// Call us at XXX-XXX-XXXX or XXX-XXX-XXXX
// Replace multiple whitespace with single space
String cleaned = "too many spaces".replaceAll("\\s+", " ");
System.out.println(cleaned); // too many spacessplit() with Regex
String.split() accepts a regex. Use it to split on multiple delimiters or complex separators.
// Split on comma with optional spaces
String csv = "Alice, Bob, Charlie,Diana";
String[] names = csv.split("\\s*,\\s*");
for (String name : names) System.out.println("'" + name + "'");
// 'Alice' 'Bob' 'Charlie' 'Diana'
// Split on any whitespace
String words = "one two\tthree four";
String[] parts = words.split("\\s+");
System.out.println(parts.length); // 4
// Limit splits
String line = "key=value=extra";
String[] kv = line.split("=", 2); // [key, value=extra]Pattern Flags
Flags modify regex behavior: CASE_INSENSITIVE, MULTILINE, DOTALL.
import java.util.regex.*;
// Case-insensitive match
Pattern p = Pattern.compile("hello", Pattern.CASE_INSENSITIVE);
System.out.println(p.matcher("HELLO World").find()); // true
// MULTILINE: ^ and $ match line boundaries
Pattern multi = Pattern.compile("^ERROR", Pattern.MULTILINE);
String logs = "INFO start\nERROR crash\nINFO end";
Matcher m = multi.matcher(logs);
int count = 0;
while (m.find()) count++;
System.out.println("ERROR lines: " + count); // 1Practical: Log Parser
Parsing Apache-style access log lines with named groups.
import java.util.regex.*;
Pattern accessLog = Pattern.compile(
"(?<ip>[\\d.]+) - - \\[(?<time>[^\\]]+)\\] " +
"\"(?<method>[A-Z]+) (?<path>[^ ]+)[^\"]*\" " +
"(?<status>\\d{3}) (?<bytes>\\d+)"
);
String line = "192.168.1.1 - - [27/May/2024:10:30:00 +0000] \"GET /api/products HTTP/1.1\" 200 1024";
Matcher m = accessLog.matcher(line);
if (m.matches()) {
System.out.println("IP: " + m.group("ip"));
System.out.println("Method: " + m.group("method"));
System.out.println("Status: " + m.group("status"));
}Quick Check
What is the difference between matches() and find() in Matcher?
Recap: Regular Expressions with Pattern and Matcher
Key takeaways:
- Pattern.compile() compiles a regex; Matcher tests it against strings
- matches() validates the whole string; find() searches for occurrences
- Capture groups () extract substrings; access with group(n) or group("name")
- Named groups (?
...) make patterns more readable - replaceAll() and split() accept regex patterns for flexible text manipulation
- Use Pattern.CASE_INSENSITIVE, MULTILINE, DOTALL flags to modify matching behavior
Frequently asked questions
Is the “Regular Expressions with Pattern and Matcher” lesson free?
Yes — the full text of “Regular Expressions with Pattern and Matcher” is free to read here on the web, and the Java Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Java Academy course, upgrade to CoddyKit PRO.
What will I learn in “Regular Expressions with Pattern and Matcher”?
Validate emails, extract substrings, and replace patterns using Java regex. You practise Java Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start Java Academy?
No prior experience is required. Java Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 4 of 4, so you can start here or from the beginning and move at your own pace.
How long does the “Regular Expressions with Pattern and Matcher” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this Java Academy lesson?
Yes. Every Java Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.
All 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