Java Regular Expressions
A regular expression (regex) is a small pattern that describes text: "three digits", "a word that starts with a capital letter", "something that looks like an email address". With a regex you can check whether input has the right form, find all matching parts in a long text, or replace them. Java's regex support is in java.util.regex, and several String methods accept a regex directly.
The building blocks
| Pattern | Matches |
|---|---|
abc | the exact text abc |
. | any one character |
[aeiou] | one of the listed characters |
[a-z] / [0-9] | one character in a range |
\d / \w / \s | a digit / a letter, digit or _ / a space |
x* / x+ / x? | x zero or more times / one or more / zero or one |
x{3} / x{2,4} | x exactly 3 times / 2 to 4 times |
^ / $ | the start / the end of the text |
(...) | a group, which can be read out later |
In Java source code a backslash inside a string must be doubled, so the regex \d is written "\\d".
Checking a whole string with matches
matches is true only when the whole string fits the pattern:
public class Main {
public static void main(String[] args) {
String pin = "411045";
System.out.println(pin.matches("\\d{6}"));
System.out.println("41104".matches("\\d{6}"));
String phone = "98765-43210";
System.out.println(phone.matches("\\d{5}-\\d{5}"));
String user = "asha_92";
System.out.println(user.matches("[a-z][a-z0-9_]{2,15}"));
}
}true false true true
This is the usual way to validate input such as PIN codes, phone numbers and user names.
Finding all matches
To find patterns inside a longer text, compile a Pattern and use a Matcher. find() moves to the next match and group() returns it:
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Main {
public static void main(String[] args) {
String text = "Order 1043 shipped on 12 May, order 1078 is waiting.";
Matcher m = Pattern.compile("\\d+").matcher(text);
while (m.find()) {
System.out.println("Number " + m.group() + " at position " + m.start());
}
}
}Number 1043 at position 6 Number 12 at position 22 Number 1078 at position 36
Groups
Round brackets mark groups, numbered from 1. They let you pull out parts of each match:
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Main {
public static void main(String[] args) {
String emails = "Contact asha@shop.in or ravi.k@mail.com for help.";
Pattern p = Pattern.compile("([\\w.]+)@([\\w.]+\\.[a-z]+)");
Matcher m = p.matcher(emails);
while (m.find()) {
System.out.println("user: " + m.group(1) + ", domain: " + m.group(2));
}
}
}user: asha, domain: shop.in user: ravi.k, domain: mail.com
Replacing and splitting
replaceAll replaces every match, and $1 in the replacement means "group 1". split cuts text wherever the pattern matches:
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
String messy = "too many spaces";
System.out.println(messy.replaceAll("\\s+", " "));
String date = "2025-08-15";
System.out.println(date.replaceAll("(\\d+)-(\\d+)-(\\d+)", "$3/$2/$1"));
String card = "1234567890123456";
System.out.println(card.replaceAll("\\d(?=\\d{4})", "*"));
System.out.println(Arrays.toString("red, green;blue yellow".split("[,;\\s]+")));
}
}too many spaces 15/08/2025 ************3456 [red, green, blue, yellow]
The third example uses a lookahead (?=...): it replaces a digit only when four more digits follow it, which hides all but the last four. Regular expressions can become hard to read quickly; keep them short and add a comment explaining what each one matches.
Practice exercises
- Check whether a text is a valid Indian vehicle number like
MH12AB1234. - Find and print all the words that start with a capital letter in a sentence.
- Replace every digit in a text with
#.