Back to Lessons

Regular Expressions in Java

April 5, 2026

Regular Expressions

Pattern matching for strings using regex.

Regex Examples

import java.util.regex.*;

// Email validation
String email = "user@example.com";
String pattern = "^[A-Za-z0-9+_.-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}$";
boolean valid = Pattern.matches(pattern, email);

// Pattern and Matcher
Pattern p = Pattern.compile("\d+"); // Digits
Matcher m = p.matcher("abc123def456");
while (m.find()) {
    System.out.println(m.group()); // 123, 456
}

Key Points

  • Common patterns: \d digits, \w word chars.
  • Pattern.compile() + Matcher.
  • matches(), find(), replaceAll() on String.
  • Quantifiers: +, *, ?, {n}.