Java Regular Expressions

A Java regular expression, often called a regex, is a pattern used to search, validate, split, or replace text. Regex is useful when the text you need is defined by a shape, such as digits, words, dates, or email-like input.

Java regex support is mainly in java.util.regex.Pattern and java.util.regex.Matcher. A Pattern stores the compiled regex, and a Matcher applies it to a specific string.

Basic Regex Syntax

Regex has special characters that describe what to match. Because Java strings also use backslashes for escapes, regex backslashes are usually written with two backslashes in Java source code.

Pattern Meaning
\d A digit, 0 through 9
\w A word character: letter, digit, or underscore
. Any single character except a line break
+ One or more of the previous item
* Zero or more of the previous item
? Zero or one of the previous item
[abc] One character from the set
^ Start of the text or line
$ End of the text or line

Example: Finding Matches

This program finds product codes in a sentence. The regex [A-Z]{2}-\d{3} means two uppercase letters, a hyphen, and three digits.

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

public class Main {
    public static void main(String[] args) {
        String text = "Orders: AB-123, xy-999, CD-456";
        Pattern codePattern = Pattern.compile("[A-Z]{2}-\\d{3}");
        Matcher matcher = codePattern.matcher(text);

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

Output:

Found: AB-123
Found: CD-456

How the Example Works

Pattern.compile(...) turns the regex into a reusable pattern. The call to matcher.find() searches for the next matching part of the text. Each time it returns true, matcher.group() returns the text that matched.

The lowercase code xy-999 is not printed because [A-Z] matches uppercase letters only.

matches() vs find()

matches() checks whether the entire input matches the pattern. find() looks for the pattern anywhere inside the input. This difference matters when validating input.

import java.util.regex.Pattern;

public class Main {
    public static void main(String[] args) {
        String phone = "555-0199";
        String text = "Call 555-0199 today";
        Pattern phonePattern = Pattern.compile("\\d{3}-\\d{4}");

        System.out.println(phonePattern.matcher(phone).matches());
        System.out.println(phonePattern.matcher(text).matches());
        System.out.println(phonePattern.matcher(text).find());
    }
}

Output:

true
false
true

Groups

Parentheses create groups. Groups let you read smaller parts of a match, such as a username and domain from an email-like string.

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

public class Main {
    public static void main(String[] args) {
        String email = "student@example.com";
        Pattern pattern = Pattern.compile("(\\w+)@(\\w+\\.\\w+)");
        Matcher matcher = pattern.matcher(email);

        if (matcher.matches()) {
            System.out.println("User: " + matcher.group(1));
            System.out.println("Domain: " + matcher.group(2));
        }
    }
}

Output:

User: student
Domain: example.com

group(0) is the whole match. group(1) is the first parenthesized group, group(2) is the second, and so on.

Replacing Text

replaceAll can replace every match with new text. The next example hides digits in a simple account number.

public class Main {
    public static void main(String[] args) {
        String account = "Account 1234-5678";
        String hidden = account.replaceAll("\\d", "*");

        System.out.println(hidden);
    }
}

Output:

Account ****-****

Practical Tips

  • Use Pattern.compile when you reuse the same regex more than once.
  • Use Pattern.CASE_INSENSITIVE when letter case should not matter.
  • Use Pattern.quote(text) when you need to search for literal text that may contain regex symbols.
  • Keep validation regexes understandable. For complicated formats, combine regex with normal Java checks.

Takeaway: Java regular expressions let you describe text patterns, then use Pattern and Matcher to find, validate, group, and replace matching text.