Regular expressions
Regex describes text patterns. In Java, use Pattern and Matcher, or String helpers.
Building blocks:
da digit,wa letter, digit or underscore,swhitespace,.any character[a-z]a range,[^0-9]anything except digits- Quantifiers:
*zero or more,+one or more,?optional,{10}exactly ten,{2,5}two to five - Anchors:
^start,$end - Groups:
(…)captures a part;(?<name>…)names it
Java strings need a double backslash, so the digit class is written "\\d" in code.
Useful methods: matches() (the whole string), find() (search), replaceAll and split. Compile a Pattern once and reuse it; compiling is the expensive part.
Example
import java.util.regex.*;
Pattern MOBILE = Pattern.compile("^(\\+91)?[6-9]\\d{9}$");
System.out.println(MOBILE.matcher("+919876543210").matches()); // true
Pattern ORDER = Pattern.compile("ORD-(?<year>\\d{4})-(?<num>\\d+)");
Matcher m = ORDER.matcher("Refund for ORD-2026-00451 and ORD-2025-9");
while (m.find()) {
System.out.println(m.group("year") + " / " + m.group("num"));
}
// 2026 / 00451
// 2025 / 9
String clean = " Hello, Java world ".trim().replaceAll("\\s+", " "); // "Hello, Java world"
String[] tags = "java, spring ,jpa".split("\\s*,\\s*"); // [java, spring, jpa]
boolean strong = "Secret123!".matches("(?=.*\\d)(?=.*[A-Z]).{8,}");Common mistake
Splitting on a dot with split("."). A dot means "any character" in regex; escape it as split("\\.").
Under the hood
String.matches compiles a new pattern on every call, so keep patterns you reuse in static final fields. Nested quantifiers such as (a+)+$ can take exponential time on crafted input (a ReDoS attack), so keep patterns on user input simple. For email addresses, a simple pattern plus a confirmation email beats a giant regex.
Check yourself
What does \d+ match?
How this connects
Know these first
Where this leads
You've reached the end of this thread. Try a learning path for what's next.
Was this lesson helpful?
Finished reading? Mark it complete to track your progress.