Regular Expressions in Java

Introduction

Regular expressions (regex) describe text patterns—for validation, search, and extraction. Java provides java.util.regex with Pattern and Matcher. Use with Strings (split, replaceAll) for everyday tasks.

Prerequisites

1) Quick String Methods

java
String email = "user@example.com";
boolean match = email.matches(".+@.+\\..+");
 
String text = "java,python,go";
String[] parts = text.split(",");
 
String cleaned = "  hello  ".replaceAll("\\s+", " ");

matches anchors to entire string (like implicit ^...$).

2) Pattern and Matcher

java
import java.util.regex.Matcher;
import java.util.regex.Pattern;
 
Pattern pattern = Pattern.compile("\\d+");
Matcher matcher = pattern.matcher("Order 12345 shipped");
 
while (matcher.find()) {
    System.out.println("Found: " + matcher.group());
}

Compile once, reuse Pattern for performance.

3) Common Metacharacters

PatternMeaning
.any char (except line break)
\ddigit
\wword char
\swhitespace
*zero or more
+one or more
?zero or one
{n,m}repeat range
^start
$end
[abc]character class

Escape backslash in Java strings: "\\d+".

4) Groups and Replacement

java
Pattern p = Pattern.compile("(\\d{4})-(\\d{2})-(\\d{2})");
Matcher m = p.matcher("2026-05-17");
if (m.matches()) {
    System.out.println("Year: " + m.group(1));
    System.out.println("Month: " + m.group(2));
    System.out.println("Day: " + m.group(3));
}
 
String redacted = "Phone: 13812345678".replaceAll("(\\d{3})\\d{4}(\\d{4})", "$1****$2");

5) Real Mini Example: Validate Username

java
public class UsernameValidator {
    private static final Pattern USERNAME = Pattern.compile("^[a-zA-Z][a-zA-Z0-9_]{2,15}$");
 
    public static boolean isValid(String username) {
        return username != null && USERNAME.matcher(username).matches();
    }
 
    public static void main(String[] args) {
        System.out.println(isValid("alice_01"));  // true
        System.out.println(isValid("1bad"));      // false
    }
}

Common Beginner Mistakes

Forgetting Double Backslashes

"\\d" in Java string → regex \d.

Use find() for searching inside longer text.

Overly Complex Regex

For simple tasks, String methods may suffice.

What’s Next

File Handling.

FAQ

Is regex the same as JavaScript regex?

Similar ideas; dialect differences exist. Test Java patterns in Java.

Performance tips?

Compile Pattern once; avoid recompiling in loops.

Tools to debug regex?

Online testers help; for JSON formatting see JSON Handling formatter link.

PatternSyntaxException?

Invalid pattern at compile time—catch when building dynamic patterns.

When not to use regex?

Parsing structured JSON/HTML—use proper parsers (JSON).