Regex in Java

Java provides regex support through java.util.regex with the Pattern and Matcher classes. Patterns must be compiled before use, and since Java strings use backslash escaping, regex backslashes need to be doubled (\\d instead of \d).

Code Examples

Basic pattern matching

import java.util.regex.*;

String text = "Order #12345 confirmed";
Pattern pattern = Pattern.compile("#(\\d+)");
Matcher matcher = pattern.matcher(text);

if (matcher.find()) {
    System.out.println(matcher.group());  // "#12345"
    System.out.println(matcher.group(1)); // "12345"
}

Pattern.compile() creates a compiled pattern. Matcher.find() searches for the next match. group(0) is the full match; group(1), group(2), etc. are capture groups.

Find all matches

import java.util.regex.*;
import java.util.List;
import java.util.ArrayList;

String text = "Temps: 72F, 65F, 80F";
Pattern pattern = Pattern.compile("(\\d+)F");
Matcher matcher = pattern.matcher(text);

List<String> temps = new ArrayList<>();
while (matcher.find()) {
    temps.add(matcher.group(1));
}
System.out.println(temps); // [72, 65, 80]

Loop with matcher.find() to iterate through all matches. Each call advances to the next match in the string.

Named capture groups

import java.util.regex.*;

String date = "2026-03-08";
Pattern pattern = Pattern.compile(
    "(?<year>\\d{4})-(?<month>\\d{2})-(?<day>\\d{2})"
);
Matcher matcher = pattern.matcher(date);

if (matcher.matches()) {
    System.out.println(matcher.group("year"));  // "2026"
    System.out.println(matcher.group("month")); // "03"
    System.out.println(matcher.group("day"));   // "08"
}

Java supports named groups with (?<name>...) syntax (added in Java 7). Access them with matcher.group("name").

String.matches() and replaceAll()

// matches() checks the ENTIRE string (anchored)
boolean valid = "hello123".matches("[a-z]+\\d+"); // true

// replaceAll() with regex
String cleaned = "  extra   spaces  ".replaceAll("\\s+", " ").trim();
System.out.println(cleaned); // "extra spaces"

// replaceAll() with backreference
String swapped = "John Smith".replaceAll(
    "(\\w+) (\\w+)", "$2, $1"
);
System.out.println(swapped); // "Smith, John"

String methods matches(), replaceAll(), and replaceFirst() accept regex strings. Note: matches() is implicitly anchored — it must match the entire string.

Pattern flags

// Case-insensitive matching
Pattern ci = Pattern.compile("hello", Pattern.CASE_INSENSITIVE);
System.out.println(ci.matcher("HELLO").matches()); // true

// Multiple flags with bitwise OR
Pattern multi = Pattern.compile(
    "^start.*end$",
    Pattern.CASE_INSENSITIVE | Pattern.DOTALL | Pattern.MULTILINE
);

// Inline flags in the pattern itself
Pattern inline = Pattern.compile("(?i)hello(?-i)WORLD");

Flags are passed as the second argument to Pattern.compile(). Common flags: CASE_INSENSITIVE (i), MULTILINE (m), DOTALL (s), COMMENTS (x). Inline flags use (?imsx) syntax.

Splitting with regex

String csv = "one, two ,three,  four";
String[] parts = csv.split("\\s*,\\s*");
// ["one", "two", "three", "four"]

// Limit the number of splits
String[] limited = "a:b:c:d:e".split(":", 3);
// ["a", "b", "c:d:e"]

String.split() accepts a regex pattern. The optional limit parameter controls the maximum number of resulting array elements.

Note

Java's regex engine does not support lookbehinds with variable-length patterns in all cases — the lookbehind length must be determinable at compile time. Since Java 9, the Matcher class has results() which returns a Stream<MatchResult> for functional-style processing. Java strings require double backslashes (\\d) because the Java compiler processes escapes before the regex engine.

Regex in Other Languages

Frequently Asked Questions

Why do I need double backslashes (\\d) in Java regex?

Java processes string escape sequences before the regex engine sees the pattern. A single backslash (\) is the Java string escape character, so \\d in Java source code becomes \d in the actual string that the regex engine receives. This is why Java regex patterns always look "noisier" than in languages with raw strings.

What is the difference between matches() and find()?

matches() requires the entire string to match the pattern (implicitly anchored with ^ and $). find() searches for the pattern anywhere within the string, like re.search() in Python. Use find() when you want to locate a pattern inside a larger string.

How do I make a regex match case-insensitive in Java?

Either pass Pattern.CASE_INSENSITIVE as the second argument to Pattern.compile(), or use the inline flag (?i) at the start of your pattern. For Unicode-aware case folding, also add Pattern.UNICODE_CASE.

Can I use regex with Java Streams?

Yes. Since Java 9, Matcher.results() returns a Stream<MatchResult>. You can also use Pattern.splitAsStream(input) to split a string lazily. Example: Pattern.compile("\\d+").matcher(text).results().map(MatchResult::group).toList().

Want to test a Java regex pattern? Our regex tester runs JavaScript's native RegExp engine in your browser — paste your pattern and see matches in real time.

← Open the Regex Tester

More Free Developer Tools