Regular Expressions (Regex) in Java provide a powerful way to search, match, validate, and manipulate text using patterns. In Advanced Java, regex is heavily used for validation, parsing logs, processing user input, and backend text handling.
., *, +[a-z]Type a pattern and text below to see the Java Matcher engine concept in action.
Java regex is provided by the java.util.regex package. The two core classes are:
Pattern — defines the regexMatcher — applies the pattern to text
// Import regex classes
import java.util.regex.Pattern;
import java.util.regex.Matcher;
// Check if a string contains only digits
String input = "12345";
String regex = "\\d+";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(input);
if (matcher.matches()) {
System.out.println("Valid number");
} else {
System.out.println("Invalid number");
}
The regex \d+ matches one or more digits. Since the input contains only digits, the matcher returns true.
// Validate an email address using regex
String email = "user@example.com";
String regex = "^[\\w.-]+@[\\w.-]+\\.[a-zA-Z]{2,6}$";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(email);
System.out.println(matcher.matches());
This pattern checks username, domain, and extension format. The output will be true for a valid email structure.
matches() for full string matchfind() for partial matches