Java provides java.util.regex
package with two main classes:
Pattern
→ Compiles the regex.Matcher
→ Used to match patterns against text.
Basic Example
import java.util.regex.*;
public class RegexExample {
public static void main(String[] args) {
String text = "My email is test@example.com";
String regex = "\\w+@\\w+\\.\\w+"; // Simple email regex
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(text);
if (matcher.find()) {
System.out.println("Found: " + matcher.group());
} else {
System.out.println("No match found.");
}
}
}
✅ Output:
Found: test@example.com
Common Regex Patterns in Java
Task | Regex | Example Match |
---|---|---|
Digits only | \\d+ | 1234 |
Letters only | [a-zA-Z]+ | Hello |
Alphanumeric | [a-zA-Z0-9]+ | User123 |
Whitespace | \\s+ | space, tab |
Word | \\w+ | hello_123 |
Email (basic) | \\w+@\\w+\\.\\w+ | abc@xyz.com |
Phone (10 digits) | \\d{10} | 9876543210 |
URL (basic) | https?://\\S+ | http://site.com |
Checking Full Match
import java.util.regex.*;
public class FullMatchExample {
public static void main(String[] args) {
String regex = "\\d{4}"; // exactly 4 digits
String input = "2025";
boolean isMatch = Pattern.matches(regex, input);
System.out.println("Match? " + isMatch);
}
}
✅ Output:
Match? true
Splitting Strings with Regex
public class SplitExample {
public static void main(String[] args) {
String text = "apple,banana;orange grape";
String[] parts = text.split("[,;\\s]+"); // split by comma, semicolon, or space
for (String word : parts) {
System.out.println(word);
}
}
}
✅ Output:
apple
banana
orange
grape
Replacing Text with Regex
public class ReplaceExample {
public static void main(String[] args) {
String text = "The price is $100.";
String result = text.replaceAll("\\$\\d+", "$XXX"); // hide price
System.out.println(result);
}
}
✅ Output:
The price is $XXX.
⚡ Notes:
- In Java strings, backslashes must be escaped.
- Regex
\d
→ Java string"\\d"
.
- Regex
- Use
Pattern.CASE_INSENSITIVE
flag for case-insensitive matches:Pattern pattern = Pattern.compile("hello", Pattern.CASE_INSENSITIVE);