Regular Expressions
A regular expression (regex) is a pattern that describes a set of strings: "six digits," "an email address," "a date like 2026-11-12," "any run of whitespace." Java uses regular expressions to validate input, find and extract parts of text, replace matches, and split strings. The core classes are Pattern and Matcher in java.util.regex; String.matches, replaceAll, replaceFirst, and split are convenient shortcuts built on them.
A First Example
boolean valid = "600042".matches("\\d{6}"); // true: exactly six digits
boolean invalid = "6000AB".matches("\\d{6}"); // false
\d means "a digit" and {6} means "exactly six times." Inside a Java string literal, every backslash must be doubled, so the regex \d{6} is written " 0 d{6}".
Pattern Syntax
Characters and classes
| Pattern | Matches |
|---|---|
abc | The literal text abc |
. | Any single character (except a line break, by default) |
[abc] | One of a, b, or c |
[a-z], [A-Z0-9] | A character in a range |
[^0-9] | Any character not listed |
\d / \D | A digit / a non-digit |
\w / \W | A word character (letter, digit, underscore) / anything else |
\s / \S | Whitespace / non-whitespace |
|