JavaRegular Expressions

Regular Expressions

A regular expression (regex) is a pattern used to search, match, or manipulate text. Java's support lives in the java.util.regex package, built around two classes: Pattern, a compiled representation of a regex, and Matcher, which applies that pattern to a specific piece of text.

A Quick One-Off Check: String.matches()

For a single, throwaway check, String has a convenience method that skips Pattern/Matcher entirely.

String.matches() for a quick check

Java
public class QuickMatchDemo {
    public static void main(String[] args) {
        String input = "12345";

        boolean isNumeric = input.matches("\\d+"); // one or more digits
        System.out.println(isNumeric);
    }
}
true
Double escaping: a common source of confusion
In a Java string literal, the backslash `\` is already the escape character. To write the regex digit class `\d`, you must escape the backslash itself, producing `\\d` in your Java source. A single, unescaped `\d` typed directly into a Java string literal is not valid regex syntax by the time it reaches the regex engine — this "escape the escape character" step trips up almost everyone the first time they write a Java regex.
Pattern and Matcher

String.matches() is convenient, but it recompiles the pattern on every call and only tells you yes/no. Pattern.compile() lets you reuse a compiled pattern, and Matcher lets you find matches, extract them, or replace them.

Compiling a pattern and finding matches

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

public class PatternMatcherDemo {
    public static void main(String[] args) {
        Pattern pattern = Pattern.compile("\\b[A-Z][a-z]*\\b");
        Matcher matcher = pattern.matcher("Alice met Bob near the River");

        while (matcher.find()) {
            System.out.println("Found: " + matcher.group());
        }
    }
}
Found: Alice
Found: Bob
Found: River
Common Use Cases

Use case

Example pattern (Java string literal)

Validate a simple email format

"^[\\w.+-]+@[\\w-]+\\.[a-zA-Z]{2,}$"

Match one or more digits

"\\d+"

Match whitespace

"\\s+"

Match a word boundary

"\\b"

Extract groups with parentheses

"(\\d{3})-(\\d{4})"

Validating an email format

Java
import java.util.regex.Pattern;

public class EmailValidationDemo {
    private static final Pattern EMAIL_PATTERN =
        Pattern.compile("^[\\w.+-]+@[\\w-]+\\.[a-zA-Z]{2,}$");

    public static void main(String[] args) {
        String[] candidates = { "user@example.com", "not-an-email" };

        for (String candidate : candidates) {
            boolean valid = EMAIL_PATTERN.matcher(candidate).matches();
            System.out.println(candidate + " -> " + valid);
        }
    }
}
user@example.com -> true
not-an-email -> false
Extracting Parts of a String With Groups

Parentheses () in a pattern create capturing groups, letting you pull specific pieces out of a larger match rather than just checking whether the whole string matches.

Extracting a phone number's area code and number

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

public class GroupExtractionDemo {
    public static void main(String[] args) {
        Pattern pattern = Pattern.compile("\\((\\d{3})\\)\\s*(\\d{3}-\\d{4})");
        Matcher matcher = pattern.matcher("Call (555) 123-4567 for support");

        if (matcher.find()) {
            System.out.println("Area code: " + matcher.group(1));
            System.out.println("Number: " + matcher.group(2));
        }
    }
}
Area code: 555
Number: 123-4567
  • Pattern.compile() compiles a regex once for reuse; Matcher applies it to actual text.

  • String.matches() is a quick shortcut for a single yes/no check.

  • Because the Java string escape character is a backslash, regex escapes must be doubled in source: two backslashes plus a letter (like d) become one backslash for the regex engine.

  • Parentheses create capturing groups, retrieved with matcher.group(n).