Module 15: Java Regular ExpressionsBeginner20 min read
Pattern, Matcher & Input Validation with Regex
Use java.util.regex.Pattern and Matcher for pattern matching, quantifiers, groups, and email/phone validation.
Key Takeaways & Core Concepts
- `Pattern.compile(regex)`: Compiles the regex string into an internal finite-state automaton. Always compile patterns once into a
static finalconstant—callingString.matches(regex)inside a loop recompiles the regex on every iteration! - `Matcher`: Stateful matching engine created by
pattern.matcher(input): - Character Classes:
\d(digit[0-9]),\w(word char[A-Za-z0-9_]),\s(whitespace),.(any char except newline). - Quantifiers:
*(0 or more),+(1 or more),?(0 or 1),{n,m}(between n and m).
Introduction
Regular expressions (java.util.regex) provide a declarative pattern language for validating emails, phone numbers, extracting structured tokens from server logs, and sanitizing user input.
Email Validation & Extracting Groups
1import java.util.regex.Matcher;
2import java.util.regex.Pattern;
3
4public class Main {
5 private static final Pattern EMAIL_PATTERN =
6 Pattern.compile("^([A-Za-z0-9+_.-]+)@([A-Za-z0-9.-]+\\.[A-Za-z]{2,})$");
7
8 public static void main(String[] args) {
9 Matcher m = EMAIL_PATTERN.matcher("dev@codezov.com");
10 if (m.matches()) {
11 System.out.println("Valid! User: " + m.group(1) + " | Domain: " + m.group(2));
12 }
13 System.out.println("bad-email valid? " + EMAIL_PATTERN.matcher("bad-email").matches());
14 }
15}
Click code or "Edit Code" to edit
Interactive Code Block•Tab = 4 spaces•Ctrl + Enter = Run
15 lines
Note: Parentheses `(...)` define capturing groups accessed via `m.group(1)` and `m.group(2)`.
Core Classes & Performance
- `Pattern.compile(regex)`: Compiles the regex string into an internal finite-state automaton. Always compile patterns once into a
static finalconstant—callingString.matches(regex)inside a loop recompiles the regex on every iteration! - `Matcher`: Stateful matching engine created by
pattern.matcher(input): matches(): Matches the entire input string from start to end.find(): Scans for the next substring occurrence (used inwhile (m.find())).group(n): Extracts captured substrings enclosed in(...).
Essential Regex Syntax
- Character Classes:
\d(digit[0-9]),\w(word char[A-Za-z0-9_]),\s(whitespace),.(any char except newline). - Quantifiers:
*(0 or more),+(1 or more),?(0 or 1),{n,m}(between n and m). - Anchors:
^(start of line/string),$(end of line/string).
Common Pitfall: ReDoS (Catastrophic Backtracking)
Nested quantifiers like (a+)+ can cause exponential backtracking on malicious input. Keep regex patterns simple, anchored, and tested against long invalid strings.
Practice & AssessmentJava Programming Tutorial
Test Your Understanding
Reinforce core concepts with interactive multiple-choice questions, live coding challenges, and top technical interview questions.
Your Current Score
0 / 0 correct(0 attempted)