Java Regex Tutorial (With Examples)
✅ What is Regex?
Regex (short for Regular Expression) is a sequence of characters that defines a search pattern. It is widely used for string pattern matching, validations, and data parsing.
In Java, regex is supported by the java.util.regex package.
Key Classes in Java Regex
Pattern: A compiled representation of a regular expression.
Matcher: An engine that performs match operations on a character sequence using a Pattern.
Basic Example
import java.util.regex.*;
public class RegexDemo {
public static void main(String[] args) {
Pattern pattern = Pattern.compile("Java");
Matcher matcher = pattern.matcher("Java is fun");
boolean matchFound = matcher.find();
System.out.println("Match found? " + matchFound); // Output: true
}
}
Common Regex Patterns
Examples
✅ 1. Check if a string contains digits
String input = "My phone number is 12345";
boolean hasDigits = input.matches(".*\\d+.*");
System.out.println(hasDigits); // true
✅ 2. Validate email address
String email = "test@example.com";
boolean isValid = email.matches("^[\\w.-]+@[\\w.-]+\\.[a-zA-Z]{2,6}$");
System.out.println(isValid); // true
✅ 3. Extract numbers from a string
String input = "Order123, Invoice456";
Pattern pattern = Pattern.compile("\\d+");
Matcher matcher = pattern.matcher(input);
while (matcher.find()) {
System.out.println("Found number: " + matcher.group());
}
✅ 4. Replace all whitespaces
String messy = "Java is \t awesome!";
String cleaned = messy.replaceAll("\\s+", " ");
System.out.println(cleaned); // Java is awesome!
✅ 5. Validate phone number (e.g., US format)
String phone = "123-456-7890";
boolean isValid = phone.matches("\\d{3}-\\d{3}-\\d{4}");
System.out.println(isValid); // true
Bonus: Pattern Flags
You can make patterns case-insensitive:
Pattern pattern = Pattern.compile("java", Pattern.CASE_INSENSITIVE);
Matcher matcher = pattern.matcher("I love Java");
System.out.println(matcher.find()); // true
Tips for Automation Testers:
Use regex in assertions with API responses.
Clean dynamic values from logs before validation.
Validate formats (email, timestamp, ID) using .matches().
Practice Exercise for You:
Write a regex to validate dates in format dd/mm/yyyy.
Extract all words starting with capital letters from a paragraph.
Replace all HTML tags with an empty string (basic HTML cleanup).