Java Regular Expressions
In this page:
import java.util.regex.*;
Pattern pattern = Pattern.compile("regex");
Matcher matcher = pattern.matcher(text);
while (matcher.find()) {
matcher.group();
}
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 so it can be used by its short name
import java.util.regex.Pattern;
// Import java.util.regex.Matcher so it can be used by its short name
import java.util.regex.Matcher;
// Define the class Main
public class Main {
// Program entry point: the JVM starts running here
public static void main(String[] args) {
Pattern pattern = Pattern.compile("cat");
Matcher matcher = pattern.matcher("The cat sat");
// Print a line to the console
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
// Define the class Main
public class Main {
// Program entry point: the JVM starts running here
public static void main(String[] args) {
// Print a line to the console
System.out.println("123".matches("\\d{3}"));
// Print a line to the console
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
// Define the class Main
public class Main {
// Program entry point: the JVM starts running here
public static void main(String[] args) {
// Declare text and set it to "cat bat rat"
String text = "cat bat rat";
// Print a line to the console
System.out.println(text.replaceAll("at", "og"));
// Print a line to the console
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
// Define the class Main
public class Main {
// Program entry point: the JVM starts running here
public static void main(String[] args) {
// Declare text and set it to "one two three"
String text = "one two three";
// Declare parts and set it to text.split("//s+")
String[] parts = text.split("\\s+");
for (String p : parts) {
// Print a line to the console
System.out.println(p);
}
}
}
Login to try C/C++/Java/PHP code in the editor
- Forgetting to escape backslashes in Java strings, so
\dmust be written"\\d". - Calling
matcher.group()without a successfulfind()ormatches(), which throwsIllegalStateException. - Using
matches()when partial matches are needed, since it must match the whole string.
- Strings are objects with many built-in methods, and
StringBuilderandStringBufferallow efficient modification. - String formatting shapes text output.
- Regular expressions match and process text patterns.
Chapter Quiz — Complete all 5 topics to unlock
0/5 topics done
Complete these topics first: