Java Regular Expressions
In this page:
Pattern and Matcher Classes
Java's regex support lives in java.util.regex, centered on two classes: Pattern compiles a regular expression once for reuse, and Matcher applies that compiled pattern against a specific input string to search, find, or check for matches.
Example: Pattern and Matcher Classes
import java.util.regex.Pattern;
import java.util.regex.Matcher;
public class Main {
public static void main(String[] args) {
Pattern pattern = Pattern.compile("cat");
Matcher matcher = pattern.matcher("The cat sat");
System.out.println(matcher.find());
}
}
Login to try C/C++/Java/PHP code in the editor
Character Classes
Character classes, written in square brackets like [aeiou] or [0-9], match any single character from the set you list — they're the building block for matching things like vowels, digit ranges, or a specific list of allowed symbols without writing out every alternative explicitly.
Example: Character Classes
public class Main {
public static void main(String[] args) {
System.out.println("hello".matches("[aeiou]+")); // false: not all vowels
System.out.println("a1".matches("[0-9]")); // false
System.out.println("5".matches("[0-9]"));
}
}
Login to try C/C++/Java/PHP code in the editor
Using Quantifiers
Quantifiers control repetition: * means zero or more, + means one or more, ? means optional (zero or one), and {n,m} lets you specify an exact or bounded repeat count, like \d{3} for exactly three digits.
Example: Using Quantifiers
public class Main {
public static void main(String[] args) {
System.out.println("123".matches("\\d{3}"));
System.out.println("color".matches("colou?r"));
System.out.println("aaa".matches("a+"));
}
}
Login to try C/C++/Java/PHP code in the editor
Replacing with Regex
replaceAll() swaps every substring matching a regex pattern with a replacement string in one call, while replaceFirst() stops after the first match — both are convenient for cleanup tasks like stripping punctuation or normalizing whitespace.
Example: Replacing with Regex
public class Main {
public static void main(String[] args) {
String text = "cat bat rat";
System.out.println(text.replaceAll("at", "og"));
System.out.println(text.replaceFirst("at", "og"));
}
}
Login to try C/C++/Java/PHP code in the editor
Splitting Strings with Regex
split() uses a regex as the delimiter to break a String into an array of pieces, which is more flexible than splitting on a single fixed character — for example, \s+ splits on any run of one or more whitespace characters, collapsing multiple spaces into a single split point.
Example: Splitting Strings with Regex
public class Main {
public static void main(String[] args) {
String text = "one two three";
String[] parts = text.split("\\s+");
for (String p : parts) {
System.out.println(p);
}
}
}
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 5 topics to unlock
0/5 topics done
Complete these topics first: