Phase 3 · Core JavaModule 20~34 min read

Regular Expressions

Match, validate, and transform text with the power of regular expressions.

What you'll learn

A regular expression (regex) is a mini-language for describing text patterns. With one compact string you can validate an email, extract dates from a document, or find-and-replace across text. It looks cryptic at first — this module makes it click.

By the end you'll be able to:

  • Read and write basic regex patterns
  • Use character classes, quantifiers, groups, and anchors
  • Search text with Pattern and Matcher
  • Validate input and perform pattern-based search & replace

Fundamentals

The simplest way to use a regex in Java is String.matches(regex), which returns true if the entire string matches the pattern. Most characters match themselves; special characters (metacharacters) describe patterns:

Basics.java
System.out.println("hello123".matches("[a-z]+[0-9]+"));  // true
System.out.println("abc".matches("[a-z]+[0-9]+"));       // false
System.out.println("2026".matches("\\d{4}"));            // true (4 digits)

Double your backslashes

Regex uses backslashes heavily (\d, \w). But a backslash is also special in Java strings, so you must write each one twice in your code — that's why the examples show \\d. The regex sees a single backslash.

Character classes

Character classes match a set of characters. These are the building blocks of most patterns:

ClassMatches
\dany digit (0–9)
\wa word character (letter, digit, or _)
\sany whitespace (space, tab, newline)
.any single character
[abc]a, b, or c
[^abc]any character except a, b, or c
[a-z]any lowercase letter (a range)

Note

Uppercase versions negate: \D is "not a digit," \W is "not a word character," \S is "not whitespace."

Quantifiers

Quantifiers say how many times the preceding element may repeat:

QuantifierMeans
*zero or more
+one or more
?zero or one (optional)
{n}exactly n times
{n,}n or more times
{n,m}between n and m times

So \d{4} matches exactly four digits, [a-z]+ matches one or more lowercase letters, and colou?r matches both "color" and "colour."

Groups & anchors

Groups — ( ) — bundle parts of a pattern and capture what they match so you can extract it. Anchors tie a match to a position: ^ is the start, $ is the end, and \b is a word boundary. Capturing groups are numbered from 1:

Groups.java
import java.util.regex.*;

Pattern p = Pattern.compile("(\\d{4})-(\\d{2})-(\\d{2})");
Matcher m = p.matcher("Date: 2026-08-23");

if (m.find()) {
    System.out.println("Year:  " + m.group(1));
    System.out.println("Month: " + m.group(2));
    System.out.println("Day:   " + m.group(3));
}

Pattern & Matcher

For anything beyond a one-off check, compile the pattern once with Pattern.compile and reuse it — it's more efficient. A Matcher then applies it to input: find() locates the next match, and group() returns the matched text. This is how you scan a document for every occurrence:

PatternMatcher.java
import java.util.regex.*;

Pattern p = Pattern.compile("\\d+");         // one or more digits
Matcher m = p.matcher("Order 42 shipped, 7 items");

while (m.find()) {
    System.out.println("Found: " + m.group());
}

Tip

matches() requires the whole string to match; find() looks for a match anywhere inside it. Choosing the wrong one is a common source of confusion.

Validation & replacement

Two everyday uses: validating input against a pattern, and replacing matches. replaceAll swaps every match — great for masking sensitive data:

Replace.java
String text = "Call 555-1234 or 555-5678";

String masked = text.replaceAll("\\d{3}-\\d{4}", "XXX-XXXX");
System.out.println(masked);
Validate.java
String regex = "^[\\w.]+@[\\w.]+\\.[a-z]{2,}$";

System.out.println("sara@example.com".matches(regex));  // true
System.out.println("bad@@nope".matches(regex));         // false

Watch out

Real-world email/phone validation is famously tricky — don't try to write the "perfect" regex. A simple sanity-check pattern plus a confirmation step (like a verification email) beats a monster regex nobody can read.

Recap & quick check

Key takeaways

  • A regex describes a text pattern; String.matches tests the whole string.
  • In Java strings, double every backslash: the regex \d is written \\d in code.
  • Character classes (\d, \w, [a-z]) match sets; quantifiers (*, +, ?, {n}) set repetition.
  • Groups ( ) capture parts for extraction; anchors ^ $ \b fix position.
  • Compile reusable patterns with Pattern; use Matcher.find() to scan, matches() to fully match.

Quick check

1. What does \d match?

2. Why do you write \\d in Java code for the regex \d?

3. The quantifier + means…

4. What's the difference between matches() and find()?

5. What do parentheses ( ) do in a regex?

Well done — you've completed Phase 3 and command the core Java libraries. Next comes Phase 4 — Advanced Java, starting with Module 21 on multithreading.