Java Regular Expressions
A regular expression (regex) is a pattern that describes a set of strings. With one compact pattern you can check whether an input looks like an email address, find all prices in a text, or split data on any mix of separators. Java's regex support lives in java.util.regex, with the classes Pattern (a compiled pattern) and Matcher (the engine that searches a string).
A first match
import java.util.regex.Matcher;
import java.util.regex.Pattern;
class Main {
public static void main(String[] args) {
Pattern pattern = Pattern.compile("java", Pattern.CASE_INSENSITIVE);
Matcher matcher = pattern.matcher("I love Java and JAVA loves me");
int count = 0;
while (matcher.find()) {
count++;
System.out.println("Found '" + matcher.group() + "' at index " + matcher.start());
}
System.out.println(count + " matches");
}
}Found 'Java' at index 7
Found 'JAVA' at index 16
2 matches
find() looks for the next occurrence anywhere in the text; group() returns the matched text.
Pattern syntax
| Pattern | Matches |
|---|---|
abc |
the literal text "abc" |
. |
any single character |
[abc] / [^abc] |
one of a, b, c / any character except these |
[a-z], [0-9] |
a character in the range |
\d / \D |
a digit / a non-digit |
\w / \W |
a word character [a-zA-Z0-9_] / anything else |
\s / \S |
whitespace / non-whitespace |
^ / $ |
start / end of the input |
\b |
a word boundary |
a|b |
a or b |
( ) |
a capturing group |
Quantifiers say how many times the previous element repeats:
| Quantifier | Meaning |
|---|---|
* |
0 or more |
+ |
1 or more |
? |
0 or 1 (optional) |
{n} / {n,} / {n,m} |
exactly n / at least n / between n and m |
Note: In Java source code a backslash must itself be escaped, so the regex
\d+is written"\\d+"in a string literal.
Validating input with matches()
String.matches(regex) checks whether the whole string matches the pattern:
class Main {
public static void main(String[] args) {
String postcode = "\\d{5}";
String email = "[\\w.+-]+@[\\w-]+(\\.[\\w-]+)+";
String hexColor = "#[0-9a-fA-F]{6}";
System.out.println("12345".matches(postcode));
System.out.println("1234a".matches(postcode));
System.out.println("ada.lovelace@example.co.uk".matches(email));
System.out.println("not-an-email".matches(email));
System.out.println("#F89820".matches(hexColor));
System.out.println("#F8982".matches(hexColor));
}
}true
false
true
false
true
false
Capturing groups
Parentheses create groups that capture part of the match. Groups are numbered from 1; group 0 is the whole match. You can also name them with (?<name>...):
import java.util.regex.Matcher;
import java.util.regex.Pattern;
class Main {
public static void main(String[] args) {
String log = """
2026-03-14 ERROR Disk almost full
2026-03-14 INFO Backup finished
2026-03-15 WARN High memory usage
""";
Pattern p = Pattern.compile("(?<date>\\d{4}-\\d{2}-\\d{2}) (?<level>[A-Z]+)\\s+(?<msg>.+)");
Matcher m = p.matcher(log);
while (m.find()) {
if (!m.group("level").equals("INFO")) {
System.out.println(m.group("level") + " on " + m.group("date") + ": " + m.group("msg"));
}
}
Matcher price = Pattern.compile("(\\d+)\\.(\\d{2})").matcher("Total: 149.95 EUR");
if (price.find()) {
System.out.println("euros=" + price.group(1) + " cents=" + price.group(2));
}
}
}ERROR on 2026-03-14: Disk almost full
WARN on 2026-03-15: High memory usage
euros=149 cents=95
Replacing and splitting
replaceAll and split accept regular expressions too. In a replacement, $1, $2 refer to captured groups:
import java.util.Arrays;
class Main {
public static void main(String[] args) {
String messy = "too many spaces here";
System.out.println(messy.replaceAll("\\s+", " "));
String phone = "Call 555-123-4567 or 555-987-6543";
System.out.println(phone.replaceAll("\\d{3}-(\\d{4})\\b", "***-$1"));
String date = "2026-10-16";
System.out.println(date.replaceAll("(\\d+)-(\\d+)-(\\d+)", "$3/$2/$1"));
String data = "apples, pears;bananas , kiwis";
System.out.println(Arrays.toString(data.split("\\s*[,;]\\s*")));
System.out.println("Price: 10 dollars".replaceAll("\\d+", "<$0>"));
}
}too many spaces here
Call 555-***-4567 or 555-***-6543
16/10/2026
[apples, pears, bananas, kiwis]
Price: <10> dollars
Tip: If you use the same pattern many times, compile it once into a
static final Patternfield.String.matchesandreplaceAllrecompile the pattern on every call.
Test yourself
Which regex matches one or more digits?
- \d*
- \d+
- \D+
- [0-9]?
What is the difference between matcher.find() and String.matches()?
- None
- find searches for a match anywhere; matches requires the whole string to match
- matches is faster
- find only works on numbers
How is the regex \s+ written inside a Java string literal?
- "\s+"
- "\\s+"
- "/s+"
- '\s+'