Regular Expressions in Java
Site Admin
· 11 Sep 2026
· 9 views
Pattern Matching in Text
A regular expression is a miniature language for describing text patterns. Java supports it through the classes Pattern and Matcher, and through convenience methods on String.
String Methods That Accept Patterns
String email = "user@example.com";
System.out.println(email.matches(".+@.+\\.com")); // true
String phone = "+91-9876543210";
String cleaned = phone.replaceAll("[^0-9]", "");
System.out.println(cleaned); // 919876543210
boolean hasDigit = "Room 42".matches(".*\\d.*"); // trueThe Core Pattern Elements
.any single character.\da digit,\wa word character,\swhitespace.[abc]a, b or c;[a-z]any lowercase letter.+one or more,*zero or more,?optional.{3}exactly three,{2,4}two to four.^start of string,$end of string.
Validation Example
boolean validEmail(String email) {
return email.matches("[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}");
}Capturing Groups
import java.util.regex.*;
Pattern p = Pattern.compile("(\\d+)-(\\d+)"); // two groups
Matcher m = p.matcher("Call 100-200 today");
if (m.find()) {
System.out.println(m.group(1)); // 100
System.out.println(m.group(2)); // 200
}Careful With Backslashes
In Java source, a regex backslash must be doubled: \d in the pattern is written as "\d" in code.
matches() must match the entire string; find() looks for a match anywhere.Key Points
- String.matches/replaceAll cover many cases without Pattern directly.
- Groups capture parts of a match for later use.
- Remember to double every backslash in Java string literals.