
Introduction
Regex (Regular Expression) is a sequence of characters used to search, match, validate, or manipulate text based on a specific pattern.
Java provides the Pattern and Matcher classes in the java.util.regex package.
1. Regex Syntax
Basic syntax:
Pattern pattern = Pattern.compile("regex");
Matcher matcher = pattern.matcher("text");
Example:
Pattern pattern = Pattern.compile("Java");
Matcher matcher = pattern.matcher("I am learning Java");
System.out.println(matcher.find());
Output:
true
2. Common Regex Patterns
| Regex | Meaning |
|---|---|
. |
Any character |
\\d |
Digit |
\\D |
Non-digit |
\\w |
Word character |
\\s |
Whitespace |
+ |
One or more |
* |
Zero or more |
? |
Zero or one |
^ |
Start of string |
$ |
End of string |
3. Check Digits
String input = "12345";
System.out.println(input.matches("\\d+"));
Output:
true
4. Check Alphabetic Characters
String input = "Java";
System.out.println(input.matches("[a-zA-Z]+"));
Output:
true
5. Validate Mobile Number
Example for a 10-digit number:
String mobile = "9876543210";
System.out.println(mobile.matches("\\d{10}"));
Output:
true
6. Validate Email
String email = "user@gmail.com";
String regex = "^[A-Za-z0-9+_.-]+@[A-Za-z0-9.-]+$";
System.out.println(email.matches(regex));
Output:
true
7. Using Pattern and Matcher
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RegexExample {
public static void main(String[] args) {
String text = "Java is powerful";
Pattern pattern = Pattern.compile("Java");
Matcher matcher = pattern.matcher(text);
if (matcher.find()) {
System.out.println("Pattern found");
}
}
}
Output:
Pattern found
8. Useful Regex Methods
matches()
Checks whether the complete string matches the pattern.
System.out.println("12345".matches("\\d+"));
find()
Searches for the pattern inside a string.
Matcher matcher = Pattern.compile("Java")
.matcher("I am learning Java");
System.out.println(matcher.find());
replaceAll()
Replaces matching characters.
String result = "Java123".replaceAll("\\d", "");
System.out.println(result);
Output:
Java
9. Common Regex Examples
\\d+ → One or more digits
[a-zA-Z]+ → Only alphabets
\\d{10} → 10 digits
^[0-9]+$ → Only numbers
^[A-Z].* → Starts with uppercase letter
\\s+ → One or more spaces
Conclusion
Java Regex is useful for pattern matching, text searching, input validation, and text replacement.
The main classes are:
Pattern→ Defines the regex patternMatcher→ Finds and matches the patternmatches()→ Checks the complete stringfind()→ Searches for a patternreplaceAll()→ Replaces matching text



