A regular expression describes a text pattern: an email address, an order number, a price. In test automation regex validates formats, extracts IDs from messages ("Order #84213 confirmed") and cleans dynamic text before comparing. Java supports it through java.util.regex.Pattern, Matcher and String methods such as matches(), replaceAll() and split().
Regex lets you describe text patterns: 'find all emails', 'validate phone numbers', 'extract dates from text'. Java's java.util.regex package provides Pattern and Matcher classes.
import java.util.regex.*;
// ── BASIC PATTERN MATCHING ──
String text = "Hello World 123";
boolean matches = text.matches("Hello.*"); // true (matches whole string)
// Pattern + Matcher (reusable, more powerful)
Pattern p = Pattern.compile("\\d+"); // compile once!
Matcher m = p.matcher(text);
while (m.find()) {
System.out.println("Found: " + m.group() + " at " + m.start());
}
// Found: 123 at 12
// ── REGEX SYNTAX ──
// . (dot) — any character except newline
// \d — digit [0-9]
// \D — non-digit
// \w — word char [a-zA-Z0-9_]
// \W — non-word char
// \s — whitespace (space, tab, newline)
// \S — non-whitespace
// ^ — start of string
// $ — end of string
// [abc] — character class: a, b, or c
// [^abc] — negated class: NOT a, b, or c
// [a-z] — range: lowercase letters
// (abc) — capturing group
// (?:abc) — non-capturing group
// a|b — alternation: a or b
// * — 0 or more
// + — 1 or more
// ? — 0 or 1 (optional)
// {n} — exactly n times
// {n,m} — n to m times
// {n,} — n or more times
// (?=abc) — positive lookahead
// (?!abc) — negative lookahead
// (?<=abc) — positive lookbehind
// (?<!abc) — negative lookbehind
// ── COMMON PATTERNS ──
String emailRegex = "^[a-zA-Z0-9._%+\\-]+@[a-zA-Z0-9.\\-]+\\.[a-zA-Z]{2,}$";
String phoneRegex = "^[+]?[(]?[0-9]{3}[)]?[-\\s.]?[0-9]{3}[-\\s.]?[0-9]{4,6}$";
String urlRegex = "https?://[\\w\\-]+(\\.[\\w\\-]+)+([\\w\\-._~:/?#\\[\\]@!$&'()*+,;=]*)?";;
String dateRegex = "^(0[1-9]|[12][0-9]|3[01])[-/](0[1-9]|1[0-2])[-/](19|20)\\d{2}$";
String ipRegex = "^((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$";
// ── GROUPS ──
Pattern datePattern = Pattern.compile("(\\d{4})-(\\d{2})-(\\d{2})");
Matcher dm = datePattern.matcher("Today is 2024-03-15");
if (dm.find()) {
System.out.println(dm.group(0)); // 2024-03-15 (whole match)
System.out.println(dm.group(1)); // 2024 (year)
System.out.println(dm.group(2)); // 03 (month)
System.out.println(dm.group(3)); // 15 (day)
}
// Named groups
Pattern named = Pattern.compile("(?<year>\\d{4})-(?<month>\\d{2})-(?<day>\\d{2})");
Matcher nm = named.matcher("2024-03-15");
if (nm.find()) {
System.out.println(nm.group("year")); // 2024
System.out.println(nm.group("month")); // 03
}
// ── REPLACE ──
String result = "hello123world456".replaceAll("\\d+", "#");
// hello#world#
// Replace with group back-reference
String r2 = "John Smith".replaceAll("(\\w+) (\\w+)", "$2, $1");
// Smith, John
// ── SPLIT ──
String[] parts = "one,two,,three".split(","); // [one, two, , three]
String[] parts2 = "one,two,,three".split(",+"); // [one, two, three] (one or more commas)
String[] parts3 = "one,two,,three".split(",", -1); // keep trailing empties
// ── FLAGS ──
Pattern ci = Pattern.compile("hello", Pattern.CASE_INSENSITIVE);
Pattern ml = Pattern.compile("^line", Pattern.MULTILINE); // ^ matches each line
Pattern dot = Pattern.compile(".", Pattern.DOTALL); // . matches newline too
Regex in Test Automation
// Extract a dynamic ID from a confirmation message
String msg = driver.findElement(By.id("toast")).getText(); // "Order #84213 confirmed"
Matcher m = Pattern.compile("Order #(\\d+)").matcher(msg);
assertTrue(m.find(), "No order number in: " + msg);
String orderId = m.group(1); // "84213"
// Validate formats returned by an API
assertTrue(response.path("phone").toString().matches("\\+91[6-9]\\d{9}"));
assertTrue(response.path("invoice").toString().matches("INV-\\d{4}-\\d{6}"));
// Normalise dynamic text before comparing
String clean = price.replaceAll("[^0-9.]", ""); // "₹1,299.00" → "1299.00"
Compile patterns you use repeatedly once (private static final Pattern ORDER = Pattern.compile(...)); String.matches() recompiles the pattern on every call.
FAQs
What is the difference between matches() and find()?
matches() requires the whole string to match the pattern; find() looks for the next match anywhere in the string.
Why do Java regex patterns need double backslashes?
The backslash is an escape character in Java string literals, so \d in a regex must be written "\\d" in Java source (text blocks behave the same).
How do you use groups in Java regex?
Wrap part of the pattern in parentheses and read it with matcher.group(1); named groups (?<id>\d+) are read with matcher.group("id").