Reading history

Java Regular Expressions (Regex) with Pattern and Matcher

5 min read 0 views

Learn Java regex: syntax cheat sheet, validating input with matches(), Pattern and Matcher, capture and named groups, split, replaceAll and lookahead, with tested examples.

A regular expression (regex) is a small pattern language for describing text: “11 digits starting with 01”, “a word followed by @”, “four digits, a dash, two digits”. Java supports regex through String.matches, split and replaceAll, and through the Pattern and Matcher classes for more control. This lesson covers the syntax you need most and shows real uses: validating phone numbers, extracting numbers, reformatting dates and masking data.

In this lesson you will learn

  • Core regex syntax: character classes, quantifiers and anchors
  • Validating input with matches()
  • Finding matches with Pattern and Matcher
  • Capture groups, named groups and back-references
  • Splitting and replacing text, and escaping in Java strings

You should know Java strings.

Matching and Finding

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Main {
    public static void main(String[] args) {
        // Validate whole strings with matches()
        String[] phones = {"01711-123456", "01911123456", "0171-12345", "02-9876543"};
        for (String p : phones) {
            System.out.println(p + " -> " + p.matches("01[3-9]\\d{2}-?\\d{6}"));
        }

        // Find every match inside a longer text
        String text = "Order #A102 cost 450 taka, order #B7 cost 1200 taka.";
        Matcher m = Pattern.compile("\\d+").matcher(text);
        StringBuilder nums = new StringBuilder();
        while (m.find()) nums.append(m.group()).append(' ');
        System.out.println("numbers: " + nums.toString().trim());

        // Capture groups pull out parts of each match
        Matcher order = Pattern.compile("#([A-Z])(\\d+) cost (\\d+)").matcher(text);
        while (order.find()) {
            System.out.println("series " + order.group(1) + ", number " + order.group(2)
                    + ", amount " + order.group(3));
        }
    }
}

Output

01711-123456 -> true
01911123456 -> true
0171-12345 -> false
02-9876543 -> false
numbers: 102 450 7 1200
series A, number 102, amount 450
series B, number 7, amount 1200
  • The phone pattern 01[3-9]\d{2}-?\d{6} reads: “01”, one digit from 3 to 9, two more digits, an optional dash, then six digits. That describes an 11-digit Bangladeshi mobile number with or without the dash.
  • String.matches checks the whole string, so no anchors are needed. “0171-12345” fails because the parts have the wrong lengths.
  • In Java source code a backslash must be doubled: the regex \d is written "\\d".
  • Pattern.compile turns the regex into a reusable object, and matcher.find() moves to the next match anywhere in the text. \d+ found every run of digits.
  • Parentheses create capture groups. group(1), group(2) and group(3) return the series letter, order number and amount from each match.

Splitting, Replacing and Groups

import java.util.Arrays;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Main {
    public static void main(String[] args) {
        // split on one or more commas, semicolons or spaces
        String tags = "java, sql;python   html,,css";
        System.out.println(Arrays.toString(tags.split("[,;\\s]+")));

        // replaceAll with a back-reference: 2026-03-26 -> 26/03/2026
        String log = "Exams: 2026-03-26 and 2026-06-10";
        System.out.println(log.replaceAll("(\\d{4})-(\\d{2})-(\\d{2})", "$3/$2/$1"));

        // Mask all but the last 3 digits of a phone number
        System.out.println("01711123456".replaceAll("\\d(?=\\d{3})", "*"));

        // Named groups and a case-insensitive flag
        Pattern email = Pattern.compile("(?<user>[\\w.]+)@(?<domain>[\\w.]+\\.[a-z]{2,})",
                Pattern.CASE_INSENSITIVE);
        Matcher m = email.matcher("Contact: Nusrat.Akter@Example.COM");
        if (m.find()) {
            System.out.println("user=" + m.group("user") + " domain=" + m.group("domain"));
        }

        // A literal dot must be escaped
        System.out.println("a.b.c".split("\\.").length + " parts, but split(\".\") gives "
                + "a.b.c".split(".").length);
    }
}

Output

[java, sql, python, html, css]
Exams: 26/03/2026 and 10/06/2026
********456
user=Nusrat.Akter domain=Example.COM
3 parts, but split(".") gives 0
  • split("[,;\\s]+") splits on any run of commas, semicolons or whitespace, so the messy tag list becomes five clean words.
  • In replaceAll, $1, $2 and $3 insert the captured groups, which rearranges ISO dates into day/month/year.
  • \d(?=\d{3}) uses a lookahead: it matches a digit only if three more digits follow, without consuming them. Every digit except the last three becomes *.
  • (?<user>…) creates a named group, read with group("user"). Pattern.CASE_INSENSITIVE lets [a-z] match capital letters too.
  • A dot means “any character” in a regex, so split(".") treats every character as a separator and returns an empty array. Escape it as "\\." to split on a real dot.

Regex Cheat Sheet

PatternMatches
.Any character except a line break
\d / \DA digit / a non-digit
\w / \sA letter, digit or underscore / whitespace
[abc], [a-z], [^0-9]One of a set, a range, anything not in the set
*, +, ?0 or more, 1 or more, 0 or 1
{n}, {n,m}Exactly n, between n and m
^, $Start and end of the input (or line)
(…), (?<name>…)Capture group, named group
a|ba or b
(?=…), (?!…)Followed by, not followed by

Common Mistakes

  1. Forgetting to double backslashes in Java strings: "\d" does not compile; write "\\d".
  2. Using matches() to search inside text. It only succeeds if the whole string matches; use Matcher.find().
  3. Splitting on "." or "|" without escaping them.
  4. Compiling the same pattern inside a loop. Store it in a static final Pattern and reuse it.

Practice Exercises

Exercise 1. Write a regex that accepts a student ID of the form CSE-2026-0042: three capital letters, a dash, a four-digit year, a dash and four digits.

Show answer
boolean ok = id.matches("[A-Z]{3}-\\d{4}-\\d{4}");
// "CSE-2026-0042" -> true, "cse-2026-42" -> false

Exercise 2. Replace every run of two or more spaces in a sentence with a single space.

Show answer
String clean = "Java   is    fun".replaceAll(" {2,}", " ");
System.out.println(clean);   // Java is fun

Frequently Asked Questions

Should I use a regex to validate email addresses?

A simple regex is fine for catching obvious typing mistakes, but the full email standard is too complex for a practical pattern. The only real test is sending a confirmation email.

What is the difference between greedy and lazy quantifiers?

.* is greedy and matches as much as possible; .*? is lazy and matches as little as possible. For "<b>x</b>", <.*> matches the whole string, while <.*?> matches just <b>.

Summary

  • Regex describes text patterns with classes, quantifiers, anchors and groups.
  • matches checks a whole string; Matcher.find searches inside one.
  • Groups extract parts and can be reused in replaceAll as $1.
  • Double every backslash in Java source code, and escape . and |.

Next: Java Inner, Nested and Anonymous Classes.

Lessons are also marked complete when you click Next.

Leave a Reply

Your email address will not be published. Required fields are marked *