Regular Expressions
A regular expression describes a pattern of text. In Java you compile it into a Pattern and use a Matcher to test, search or extract. This page explains how the engine works, tours the syntax, compares matches, lookingAt and find, covers groups, flags and lookaround, shows a pattern whose run time explodes, and measures what precompiling saves.
Contents
How Java's regex engine works
java.util.regex.*a|b
The API has two main classes with different roles:
is the compiled form of a regex. Compiling parses the pattern into a tree of nodes, which takes time, so a pattern used repeatedly should be compiled once. APattern is immutable and safe to share between threads.Pattern applies a pattern to one input and holds the state of the search: the current position and the groups of the last match. It is not thread-safe, but it can be reused withMatcher .reset
| API | Since | Best for |
|---|---|---|
Pattern.compileMatcher.matchesfindlookingAt | Java 1.4 | Everything; compile once, match many times |
String.matchesreplaceAllsplit | Java 1.4 | One-off use; they compile the pattern on every call |
Named groups (?<name>...) | Java 7 | Readable extraction |
Pattern.asPredicatesplitAsStream | Java 8 | Streams and filters |
Matcher.results()replaceAll(Function) | Java 9 | All matches as a stream; computed replacements |
Pattern.asMatchPredicate | Java 11 | Filtering by a whole-string match |
Pattern.namedGroups()Matcher.namedGroups() | Java 20 | Listing a pattern's group names |
Replacing text is covered on the
The syntax in one program
Each line of output applies one construct to the same sentence, which contains names, an underscore, integers, a decimal, a negative number and a date, so every construct has something to find. In Java source each backslash is doubled, so the regex \d"\\d"
import java.util.List;
import java.util.regex.Pattern;
public class SyntaxTour {
public static void main(String[] args) {
String text = "Ann: 42, Bob_7: 3.5, Zoe: -8 (2026-11-14)";
show("\\d", text); // a digit
show("\\d+", text); // one or more digits
show("\\w+", text); // word characters: letters, digits, _
show("[A-Z]\\w*", text); // character class, then zero or more
show("[^\\w\\s]", text); // negated class: not word, not space
show("-?\\d+(?:\\.\\d+)?", text); // optional sign and optional fraction
show("\\d{4}-\\d{2}-\\d{2}", text); // exact counts
show("\\b\\w{3}\\b", text); // \b: word boundary
show("^\\w+", text); // ^: start of input
show("\\d+(?=\\))", text); // lookahead: digits followed by )
show("(?<=: )\\w+", text); // lookbehind: after ": "
show("Ann|Zoe", text); // alternation
}
static void show(String regex, String text) {
List<String> found = Pattern.compile(regex).matcher(text).results()
.map(r -> r.group()).toList();
System.out.printf("%-22s %s%n", regex, found);
}
}
Output:
\d [4, 2, 7, 3, 5, 8, 2, 0, 2, 6, 1, 1, 1, 4]
\d+ [42, 7, 3, 5, 8, 2026, 11, 14]
\w+ [Ann, 42, Bob_7, 3, 5, Zoe, 8, 2026, 11, 14]
[A-Z]\w* [Ann, Bob_7, Zoe]
[^\w\s] [:, ,, :, ., ,, :, -, (, -, -, )]
-?\d+(?:\.\d+)? [42, 7, 3.5, -8, 2026, -11, -14]
\d{4}-\d{2}-\d{2} [2026-11-14]
\b\w{3}\b [Ann, Zoe]
^\w+ [Ann]
\d+(?=\)) [14]
(?<=: )\w+ [42, 3]
Ann|Zoe [Ann, Zoe]
| Construct | Meaning |
|---|---|
\d\w\s | A digit, a word character (letter, digit or _\D\W\S |
[A-Z][^...] | One character from a set or range; ^ |
*+?{n}{n,m} | Zero or more, one or more, optional, exactly n, between n and m |
(...)(?:...) | A capturing group, and a group that only groups |
^$\b | Start and end of input (or of a line with MULTILINE |
(?=...)(?<=...) | Lookahead and lookbehind: check what follows or precedes without consuming it |
a|b | Either alternative, tried left to right |
found\w+ as one word, because the underscore and digits are word characters, but splitBob_7 into3.5 and3 .5- The number pattern
found 3.5 and -8 correctly, but also read the date as 2026, -11 and -14. A regex matches what you wrote, not what you meant; tests with awkward input catch this.-?\d+(?:\.\d+)? found only\b\w{3}\b andAnn :Zoe requires a boundary on both sides, so the three-letter start of\b does not count.Bob_7- The lookahead found only 14, the digits right before
, and the lookbehind found the values after) without including the colon.": "
matches, lookingAt and find
The three ways of applying a pattern differ in how much of the input must match, and confusing them is the most common regex bug in Java. The sentence contains two numbers, but does not start or consist of one.
import java.util.List;
import java.util.function.Predicate;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class MatchVsFind {
public static void main(String[] args) {
Pattern digits = Pattern.compile("\\d+");
String text = "Order 66 shipped in 3 boxes";
System.out.println("matches(): " + digits.matcher(text).matches()); // whole input?
System.out.println("lookingAt(): " + digits.matcher(text).lookingAt()); // at the start?
System.out.println("find(): " + digits.matcher(text).find()); // anywhere?
System.out.println("lookingAt() on \"66 boxes\": "
+ digits.matcher("66 boxes").lookingAt());
Matcher m = digits.matcher(text);
while (m.find()) {
System.out.println("found \"" + m.group() + "\" at " + m.start() + ".." + m.end());
}
// Java 9+: all matches as a stream
System.out.println("results(): "
+ digits.matcher(text).results().map(r -> r.group()).toList());
// Predicates for filtering: asPredicate finds, asMatchPredicate (Java 11) matches
List<String> inputs = List.of("123", "abc", "12a", "007");
Predicate<String> containsDigits = digits.asPredicate();
Predicate<String> allDigits = digits.asMatchPredicate();
System.out.println("asPredicate: " + inputs.stream().filter(containsDigits).toList());
System.out.println("asMatchPredicate: " + inputs.stream().filter(allDigits).toList());
// String.matches must match the whole string: a common surprise
System.out.println("\"id 42\".matches(\"\\\\d+\") = " + "id 42".matches("\\d+"));
System.out.println("\"id 42\".matches(\".*\\\\d+\") = " + "id 42".matches(".*\\d+"));
}
}
Output:
matches(): false
lookingAt(): false
find(): true
lookingAt() on "66 boxes": true
found "66" at 6..8
found "3" at 20..21
results(): [66, 3]
asPredicate: [123, 12a, 007]
asMatchPredicate: [123, 007]
"id 42".matches("\\d+") = false
"id 42".matches(".*\\d+") = true
succeeds only if the whole input matches,matches() if the start does, andlookingAt() if any part does. Onlyfind() succeeded on the sentence;find succeeded onlookingAt .66 boxes- Each call to
continues after the previous match, so afind() loop visits every match.while (m.find()) andstart() give the half-open range of each one:end() is at 6..8.66 returns the matches as aresults() , which replaces the loop when you only need the values.Stream<MatchResult> usesasPredicate() , so it keptfind .12a usesasMatchPredicate() and kept only the all-digit strings. Choosing the wrong one silently lets invalid input through a validation filter.matches always tests the whole string, soString.matches is false. Adding"id 42".matches("\\d+") makes it true, but.* says what you mean.Pattern.compile("\\d+").matcher(s).find()
Capturing groups
Groups extract parts of a match. The log format here has an optional user field in brackets, so the program can show what an unmatched group returns, along with greedy and lazy matching on HTML-like text.
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Groups {
// Named groups document what each part means
static final Pattern LOG = Pattern.compile(
"(?<date>\\d{4}-\\d{2}-\\d{2}) (?<level>INFO|WARN|ERROR)"
+ "(?: \\[(?<user>\\w+)])? (?<msg>.*)");
public static void main(String[] args) {
for (String line : new String[] {"2026-11-14 WARN [ann] disk 91% full",
"2026-11-14 INFO started"}) {
Matcher m = LOG.matcher(line);
if (m.matches()) {
System.out.printf("date=%s level=%s user=%s msg=%s%n", m.group("date"),
m.group("level"), m.group("user"), m.group("msg"));
}
}
Matcher m = LOG.matcher("2026-11-14 WARN [ann] disk 91% full");
m.matches();
System.out.println("groupCount() = " + m.groupCount() + ", group(0) = " + m.group(0));
System.out.println("level spans " + m.start("level") + ".." + m.end("level"));
System.out.println("namedGroups() = " + new java.util.TreeMap<>(LOG.namedGroups()));
// Asking for a group before a successful match throws
try {
LOG.matcher("bad").group(1);
} catch (IllegalStateException e) {
System.out.println("group() without a match: " + e.getMessage());
}
// Greedy vs lazy: .* takes as much as possible, .*? as little as possible
String html = "<b>one</b> and <b>two</b>";
Matcher greedy = Pattern.compile("<b>(.*)</b>").matcher(html);
Matcher lazy = Pattern.compile("<b>(.*?)</b>").matcher(html);
greedy.find();
lazy.find();
System.out.println("greedy: " + greedy.group(1));
System.out.println("lazy: " + lazy.group(1));
Pattern negated = Pattern.compile("<b>([^<]*)</b>");
System.out.println("negated class: "
+ negated.matcher(html).results().map(r -> r.group(1)).toList());
// A repeated group keeps only its last repetition
Matcher rep = Pattern.compile("(\\d)+").matcher("2026");
rep.matches();
System.out.println("(\\d)+ on 2026: group(1) = " + rep.group(1));
// A backreference \1 repeats what group 1 matched
Matcher doubled = Pattern.compile("\\b(\\w+) \\1\\b").matcher("the the cat sat sat down");
while (doubled.find()) {
System.out.println("doubled word: " + doubled.group(1));
}
}
}
Output:
date=2026-11-14 level=WARN user=ann msg=disk 91% full
date=2026-11-14 level=INFO user=null msg=started
groupCount() = 4, group(0) = 2026-11-14 WARN [ann] disk 91% full
level spans 11..15
namedGroups() = {date=1, level=2, msg=4, user=3}
group() without a match: No match found
greedy: one</b> and <b>two
lazy: one
negated class: [one, two]
(\d)+ on 2026: group(1) = 6
doubled word: the
doubled word: sat
- Named groups make the code read like the data. A group inside an optional part that did not take part in the match returns
, asnull did for the second line, so check before using it.user - Groups are numbered by their opening parenthesis from left to right, and
is not counted, so there are 4 groups.(?:...) is the whole match.group(0) andstart("level") give 11..15.end("level") , new in Java 20, returns the map from names to numbers.namedGroups()- Calling
before a successfulgroup ormatches throwsfind with "No match found".IllegalStateException - Greedy
takes as much as possible and then backs off, so it matched from the first.* to the last<b> . Lazy</b> takes as little as possible. A negated class such as.*? is usually better than either: it cannot run past the next tag, and it backtracks less.[^<]* - A repeated group keeps only its last repetition, so
on 2026 gives(\d)+ . To get every repetition, use6 in a loop.find refers back to what group 1 matched, which finds the two words written twice in a row.\1
Flags and Unicode
Flags change how the whole pattern is read. They can be passed to Pattern.compile(?i)
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;
public class Flags {
public static void main(String[] args) {
// Case-insensitive, as a flag or inline; UNICODE_CASE for letters beyond ASCII
System.out.println("CASE_INSENSITIVE JaVa: "
+ Pattern.compile("java", Pattern.CASE_INSENSITIVE).matcher("JaVa").matches());
System.out.println("(?i) on \u00C9T\u00C9 vs \u00E9t\u00E9: "
+ "\u00C9T\u00C9".matches("(?i)\u00E9t\u00E9"));
System.out.println("(?iu) on \u00C9T\u00C9 vs \u00E9t\u00E9: "
+ "\u00C9T\u00C9".matches("(?iu)\u00E9t\u00E9"));
// MULTILINE: ^ and $ match at every line, not just the ends of the input
String lines = "id=1\nname=ann\nid=2";
Pattern id = Pattern.compile("^id=(\\d+)$", Pattern.MULTILINE);
System.out.println("MULTILINE ids: "
+ id.matcher(lines).results().map(r -> r.group(1)).toList());
Pattern plain = Pattern.compile("^id=(\\d+)$");
System.out.println("without: "
+ plain.matcher(lines).results().map(r -> r.group(1)).toList());
// DOTALL: . also matches newlines
System.out.println("a.b on a\\nb without DOTALL: " + Pattern.matches("a.b", "a\nb"));
System.out.println("a.b on a\\nb with (?s): " + Pattern.matches("(?s)a.b", "a\nb"));
// \w and \d are ASCII-only unless UNICODE_CHARACTER_CLASS is set
String word = "na\u00EFve";
System.out.println("\\w+ on na\u00EFve: " + word.matches("\\w+"));
System.out.println("(?U)\\w+ on na\u00EFve: " + word.matches("(?U)\\w+"));
System.out.println("\\p{L}+ on na\u00EFve: " + word.matches("\\p{L}+"));
// COMMENTS: whitespace ignored and # starts a comment, for readable patterns
Pattern date = Pattern.compile("""
(\\d{4}) # year
-(\\d{2}) # month
-(\\d{2}) # day
""", Pattern.COMMENTS);
System.out.println("COMMENTS date: " + date.matcher("2026-11-14").matches());
// Bad patterns fail when compiled, with the position of the error
try {
Pattern.compile("(unclosed");
} catch (PatternSyntaxException e) {
System.out.println("PatternSyntaxException: " + e.getDescription()
+ " near index " + e.getIndex());
}
}
}
Output:
CASE_INSENSITIVE JaVa: true
(?i) on ÉTÉ vs été: false
(?iu) on ÉTÉ vs été: true
MULTILINE ids: [1, 2]
without: []
a.b on a\nb without DOTALL: false
a.b on a\nb with (?s): true
\w+ on naïve: false
(?U)\w+ on naïve: true
\p{L}+ on naïve: true
COMMENTS date: true
PatternSyntaxException: Unclosed group near index 9
| Flag | Inline | Effect |
|---|---|---|
CASE_INSENSITIVE | (?i) | Ignore case, for ASCII letters only |
UNICODE_CASE | (?u) | With (?i) |
MULTILINE | (?m) | ^$ |
DOTALL | (?s) | . |
UNICODE_CHARACTER_CLASS | (?U) | \w\d\s\b |
COMMENTS | (?x) | Ignore whitespace and allow # |
alone did not match(?i) againstÉTÉ ; addingété did.u- Without
,MULTILINE found nothing in the three-line text, because^id=(\d+)$ and^ refer to the whole input. With it, both ids were found.$ rejected\w+ , becausenaïve means\w by default.[a-zA-Z_0-9] or the Unicode property(?U)\w+ (any letter) accept it. This matters for validating names.\p{L} with a text block lets a long pattern be written over several lines with a comment per part.COMMENTS- A syntax error throws
at compile time, with a description and the index, here 9, the end of the pattern. Compiling patterns intoPatternSyntaxException fields makes such errors appear when the class loads, not deep inside a request.static final
Lookahead and lookbehind in practice
Lookaround checks a condition at a position without consuming characters, which lets one pattern test several independent rules. The examples are typical uses: a password policy, digit grouping, and extracting values next to a marker.
import java.util.List;
import java.util.regex.Pattern;
public class Lookaround {
// Each lookahead checks one rule from the start, without consuming characters
static final Pattern PASSWORD = Pattern.compile(
"^(?=.*\\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[^\\w\\s]).{10,}$");
public static void main(String[] args) {
for (String pw : List.of("short1A!", "longenough1!", "LongEnough1!", "LongEnough12")) {
System.out.printf("%-14s %s%n", pw, PASSWORD.matcher(pw).matches() ? "ok" : "rejected");
}
// Thousands separators: a position followed by groups of three digits up to the end
System.out.println("1234567 -> " + "1234567".replaceAll("\\B(?=(\\d{3})+$)", ","));
// Negative lookahead: words that are not followed by "Exception"
String types = "IOException Reader TimeoutException Writer";
System.out.println("not exceptions: " + Pattern.compile("\\b\\w+\\b(?<!Exception)")
.matcher(types).results().map(r -> r.group()).toList());
// Lookbehind: amounts after a currency sign, without the sign
System.out.println("after $: " + Pattern.compile("(?<=\\$)\\d+(?:\\.\\d{2})?")
.matcher("Paid $12.50, owed $7 and 9 points").results().map(r -> r.group()).toList());
}
}
Output:
short1A! rejected
longenough1! rejected
LongEnough1! ok
LongEnough12 rejected
1234567 -> 1,234,567
not exceptions: [Reader, Writer]
after $: [12.50, 7]
- The password pattern has four lookaheads at the start, one per rule: a digit, a lowercase letter, an uppercase letter, and a symbol. Each scans ahead and returns to the start, then
checks the length..{10,} lacks an uppercase letter andlongenough1! lacks a symbol.LongEnough12 matches the empty positions inside the number that are followed by a multiple of three digits, so replacing them with commas gives\B(?=(\d{3})+$) . For real formatting,1,234,567 is clearer; seeNumberFormatnumbers and strings .- The negative lookbehind
after a word rejects words that end in(?<!Exception) .Exception found 12.50 and 7 after dollar signs, but not 9, and left the sign out of the match.(?<=\$)
Catastrophic backtracking
Because the engine tries alternatives one by one, a pattern that can match the same text in many ways may take exponential time when the match finally fails. The input here is a run of a
public class Backtracking {
public static void main(String[] args) {
// Each .* can stop at any 'a', so the engine tries every way of splitting
// the input into 21 pieces before giving up on the missing 21st 'a'
for (int n : new int[] {16, 18, 20, 22, 24}) {
String input = "a".repeat(n) + "!";
time("(.*a){21}, n=" + n, () -> input.matches("(.*a){21}"));
}
String input = "a".repeat(24) + "!";
time("[^a]*(a[^a]*){21}, n=24", () -> input.matches("[^a]*(a[^a]*){21}"));
// Possessive quantifiers never give characters back, which can also prevent a match
System.out.println("\"aaa\".matches(\"a*a\") = " + "aaa".matches("a*a"));
System.out.println("\"aaa\".matches(\"a*+a\") = " + "aaa".matches("a*+a"));
// Deep recursion: alternation inside a repeated group uses stack per character
String longText = "ab".repeat(20000);
try {
System.out.println("(a|b)* on 40,000 chars: " + longText.matches("(a|b)*"));
} catch (StackOverflowError e) {
System.out.println("(a|b)* on 40,000 chars: StackOverflowError");
}
System.out.println("[ab]* on 40,000 chars: " + longText.matches("[ab]*"));
}
interface Check {
boolean run();
}
static void time(String label, Check check) {
long t0 = System.nanoTime();
boolean matched = check.run();
System.out.printf("%-26s matched=%b in %,8.1f ms%n", label, matched,
(System.nanoTime() - t0) / 1e6);
}
}
Output (single runs on a 2-CPU Linux machine, JDK 21; the growth matters, not the exact times):
(.*a){21}, n=16 matched=false in 11.8 ms
(.*a){21}, n=18 matched=false in 15.6 ms
(.*a){21}, n=20 matched=false in 41.3 ms
(.*a){21}, n=22 matched=false in 86.6 ms
(.*a){21}, n=24 matched=false in 319.0 ms
[^a]*(a[^a]*){21}, n=24 matched=false in 0.5 ms
"aaa".matches("a*a") = true
"aaa".matches("a*+a") = false
(a|b)* on 40,000 chars: StackOverflowError
[ab]* on 40,000 chars: true
- In
, each(.*a){21} can stop before any of the.* characters, so the number of ways to divide the input grows combinatorially. Every two extra characters made the failing match roughly two to four times slower. A few more characters, or a pattern like this applied to a long user-supplied string, can hang a thread for minutes: a regex denial-of-service, or ReDoS.a - The unambiguous version,
, describes the same strings, but there is only one way to match each part, so it failed in well under a millisecond.[^a]*(a[^a]*){21} - Possessive quantifiers such as
and atomic groups*+ never give characters back, which removes backtracking. They also change the meaning:(?>...) cannot matcha*+a , becauseaaa keeps all three letters.a*+ - Alternation inside a repeated group,
, recurses once per repetition, and on 40,000 characters it threw(a|b)* . The character classStackOverflowError matches the same input without recursion.[ab]*
Rules of thumb: avoid nested quantifiers over the same characters, prefer character classes to alternation, and limit the length of untrusted input before matching it.
What precompiling saves
The program validates a million product codes such as ABC-1234String.matches
import java.util.function.Predicate;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RegexSpeed {
static final Pattern CODE = Pattern.compile("[A-Z]{3}-\\d{4}");
public static void main(String[] args) {
String[] inputs = new String[1000000];
for (int i = 0; i < inputs.length; i++) {
inputs[i] = (i % 2 == 0 ? "ABC-" : "AB1-") + (1000 + i % 9000);
}
time("String.matches", inputs, s -> s.matches("[A-Z]{3}-\\d{4}"));
time("static final Pattern", inputs, s -> CODE.matcher(s).matches());
Matcher reused = CODE.matcher("");
time("reused Matcher.reset", inputs, s -> reused.reset(s).matches());
time("hand-written check", inputs, RegexSpeed::check);
}
static boolean check(String s) {
if (s.length() != 8 || s.charAt(3) != '-') {
return false;
}
for (int i = 0; i < 8; i++) {
char c = s.charAt(i);
if (i < 3 && (c < 'A' || c > 'Z') || i > 3 && (c < '0' || c > '9')) {
return false;
}
}
return true;
}
// Best of 3 runs
static void time(String name, String[] inputs, Predicate<String> p) {
long best = Long.MAX_VALUE;
int ok = 0;
for (int run = 0; run < 3; run++) {
ok = 0;
long t0 = System.nanoTime();
for (String s : inputs) {
if (p.test(s)) {
ok++;
}
}
best = Math.min(best, System.nanoTime() - t0);
}
System.out.printf("%-22s %6.1f ms %,d valid%n", name, best / 1e6, ok);
}
}
Output (rough figures from a 2-CPU Linux machine running JDK 21):
String.matches 191.7 ms 500,000 valid
static final Pattern 51.1 ms 500,000 valid
reused Matcher.reset 59.0 ms 500,000 valid
hand-written check 17.2 ms 500,000 valid
compiles the pattern on every call and was about four times slower than the same pattern compiled once into aString.matches field.static final- Reusing one
withMatcher saves creating a matcher per input, but it made little difference across runs, sometimes faster and sometimes slower. Creating areset(input) is cheap, and a shared one must stay on one thread.Matcher - A hand-written check for this simple format was faster still. For fixed formats in hot code that can be worth it; for anything more complex, a precompiled pattern is the better balance of speed and clarity.
Choosing the right regex API
| Goal | Use |
|---|---|
| Does the whole string have this format? | PATTERN.matcher(s).matches() |
| Does the string contain the pattern? | PATTERN.matcher(s).find() |
| Every match | while (m.find())m.results() |
| Parts of a match | Named groups, checking optional groups for null |
| Filter a stream | asMatchPredicate()asPredicate() |
| Same pattern used repeatedly | A static final Pattern |
| Letters beyond ASCII | \p{L}(?U)(?iu) |
| Untrusted input or long strings | Unambiguous patterns, character classes, and a length limit |
| Text with user-supplied parts | Pattern.quote |