Java RegEx
Pattern matching with regular expressions
🔍 What is RegEx?
Regular Expressions (RegEx) are patterns used to match character combinations in strings. Java provides powerful RegEx support for text processing and validation.
import java.util.regex.Pattern;
// Simple pattern matching
String text = "Hello World";
boolean matches = Pattern.matches("Hello.*", text);
System.out.println(matches); // true
Output:
matches: true
"Hello.*" matches any string starting with "Hello"
RegEx Components
Pattern
Compiled regular expression
Pattern pattern = Pattern.compile("\\d+");
Matcher
Engine for pattern matching
Matcher matcher = pattern.matcher(text);
Metacharacters
Special pattern characters
. * + ? ^ $ | [] {} ()
Character Classes
Predefined character sets
\\d \\w \\s [a-z] [0-9]
🔹 Basic Pattern Matching
Simple examples of pattern matching in Java:
import java.util.regex.*;
public class BasicRegEx {
public static void main(String[] args) {
String text = "The price is $25.99";
// Check if text contains digits
boolean hasDigits = Pattern.matches(".*\\d.*", text);
System.out.println("Has digits: " + hasDigits);
// Find all numbers
Pattern numberPattern = Pattern.compile("\\d+\\.?\\d*");
Matcher matcher = numberPattern.matcher(text);
while (matcher.find()) {
System.out.println("Found number: " + matcher.group());
}
// Validate email format
String email = "[email protected]";
String emailRegex = "^[A-Za-z0-9+_.-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}$";
boolean validEmail = Pattern.matches(emailRegex, email);
System.out.println("Valid email: " + validEmail);
}
}
Output:
Has digits: true
Found number: 25.99
Valid email: true
🔹 Common RegEx Patterns
Useful regular expression patterns for validation:
import java.util.regex.Pattern;
public class CommonPatterns {
// Phone number validation (US format)
public static boolean isValidPhone(String phone) {
String phoneRegex = "^\$$\\d{3}\$$\\s\\d{3}-\\d{4}$";
return Pattern.matches(phoneRegex, phone);
}
// Password strength check
public static boolean isStrongPassword(String password) {
// At least 8 chars, 1 uppercase, 1 lowercase, 1 digit
String passwordRegex = "^(?=.*[a-z])(?=.*[A-Z])(?=.*\\d).{8,}$";
return Pattern.matches(passwordRegex, password);
}
// Extract words from text
public static void extractWords(String text) {
Pattern wordPattern = Pattern.compile("\\b\\w+\\b");
Matcher matcher = wordPattern.matcher(text);
System.out.println("Words found:");
while (matcher.find()) {
System.out.println("- " + matcher.group());
}
}
public static void main(String[] args) {
// Test phone validation
System.out.println(isValidPhone("(123) 456-7890")); // true
System.out.println(isValidPhone("123-456-7890")); // false
// Test password strength
System.out.println(isStrongPassword("Password123")); // true
System.out.println(isStrongPassword("password")); // false
// Extract words
extractWords("Hello, World! How are you?");
}
}
Output:
true
false
true
false
Words found: Hello, World, How, are, you
🔹 String Methods with RegEx
Using regular expressions with String methods:
public class StringRegEx {
public static void main(String[] args) {
String text = "Java is great! Java is powerful. Java is fun.";
// Split string using regex
String[] sentences = text.split("\\.");
System.out.println("Sentences:");
for (String sentence : sentences) {
System.out.println("- " + sentence.trim());
}
// Replace using regex
String replaced = text.replaceAll("Java", "Python");
System.out.println("Replaced: " + replaced);
// Replace first occurrence only
String replacedFirst = text.replaceFirst("Java", "C++");
System.out.println("First replaced: " + replacedFirst);
// Check if string matches pattern
String number = "12345";
boolean isNumber = number.matches("\\d+");
System.out.println("Is number: " + isNumber);
// Remove all non-alphabetic characters
String messy = "H3ll0 W0rld!@#";
String clean = messy.replaceAll("[^a-zA-Z\\s]", "");
System.out.println("Cleaned: " + clean);
}
}
Output:
Sentences: Java is great!, Java is powerful, Java is fun
Replaced: Python is great! Python is powerful. Python is fun.
First replaced: C++ is great! Java is powerful. Java is fun.
Is number: true
Cleaned: Hll Wrld