Java Regex - Complete Guide
Java Regex - Complete Summary
1. Basic Syntax
| Pattern | Meaning | Example | Matches |
|---------|----------------------------------|----------------|----------------------------------|
|. | Any character except newline | a.c | abc, axc, a#c |
| \d | Digit [0-9] | \d\d | 12, 45, 09 |
| \D | Non-digit | \D | a, -, @ |
| \w | Word char (a-zA-Z0-9_) | \w\w | ab, A1, x_ |
| \W | Non-word char | \W | #, @, ! |
| \s | Whitespace | \s | Space, tab, newline |
| \S | Non-whitespace | \S | a, 5, @ |
|^ | Start of string | ^abc | abcde |
|$ | End of string | xyz$ | 123xyz |
| [] | Character class | [a-c] | a, b, c |
| [^] | Negated character class | [^0-9] | Any non-digit |
|| | OR operator | cat|dog | cat, dog |
| () | Grouping | (ab)+ | abab, ab |
2. Quantifiers
| Quantifier | Meaning | Example | Matches |
|------------|-----------------------------------|---------------|---------------------------------|
|* | 0 or more | a* | "", a, aaaa |
|+ | 1 or more | a+ | a, aa, aaaa |
|? | 0 or 1 | a? | "", a |
| {n} | Exactly n | a{3} | aaa |
| {n,} | n or more | a{2,} | aa, aaa, aaaa |
| {n,m} | Between n and m | a{2,4} | aa, aaa, aaaa |
3. Java Regex API Usage
import java.util.regex.*;
public class Main {
public static void main(String[] args) {
String text = "My number is 12345.";
String pattern = "\\d+";
Pattern p = Pattern.compile(pattern);
Matcher m = p.matcher(text);
while (m.find()) {
System.out.println("Found: " + m.group());
}
}
}
4. Useful Regex Examples
| Use Case | Pattern |
|--------------------------|------------------------------|
| Validate email | [\w.-]+@[\w.-]+\.\w+ |
| Only digits | ^\d+$ |
| Only letters | ^[a-zA-Z]+$ |
| Phone number (10 digits) | ^\d{10}$ |
| Password (min 8 chars, 1 digit, 1 letter) | ^(?=.*[A-Za-z])(?=.*\d).{8,}$ |
5. Pattern Flags
| Flag | Meaning |
|---------------------------|----------------------------------|
| Pattern.CASE_INSENSITIVE | Ignores case |
| Pattern.MULTILINE | ^ and $ match line starts/ends |
| Pattern.DOTALL | . matches newline too |
Usage:
Pattern p = Pattern.compile("abc", Pattern.CASE_INSENSITIVE);