Java Regex — Free Java Tutorial
Learn Java Regex in Java with a free, beginner-friendly tutorial, examples and practice for Indian students on Syllab.in.
TL;DR: Learn Java Regex in Java with a free, beginner-friendly tutorial, examples and practice for Indian students on Syllab.in.
Written & reviewed by the Syllab.in Academic Team (CBSE/NCERT subject experts) · Updated
Java Regex in Java
Regular expressions (regex) are patterns for matching, searching, and manipulating text. Java provides them through java.util.regex (Pattern, Matcher) and String methods.
Common patterns: \d (digit), \w (word char), \s (whitespace), . (any char), * (0+), + (1+), ? (0 or 1), {n} (exactly n), {n,m} (n to m), ^ (start), $ (end), [] (character class), | (or), () (group).
Pattern.compile() compiles the regex (expensive — cache it). Matcher checks the pattern against input: matches() (full match), find() (substring match), group() (captured group).
String shortcuts: s.matches(regex), s.replaceAll(regex, replacement), s.split(regex) — these create a new Pattern each call, so use Pattern.compile() in loops.
Java Regex — Syntax
import java.util.regex.*;
Pattern p = Pattern.compile("\\d{3}-\\d{4}");
Matcher m = p.matcher("Call 555-1234 now");
while (m.find()) {
System.out.println("Found: " + m.group()); // 555-1234
}
// String shortcuts
"hello123".matches("[a-z]+\\d+"); // true
"a1b2c3".replaceAll("\\d", "X"); // "aXbXcX"
"a,b,,c".split(",+"); // ["a","b","c"]
Learn Java Regex step by step with Syllab's free interactive Java tutorial — runnable code examples, practice exercises and instant AI feedback, all free with no signup. Explore the full Java course →