Course map
Stage 1: Foundation
Stage 2: Intermediate
Stage 3: Advanced
Stage 4: DSA in Java
Stage 5: Specialization

Part 11 / Topic 5 of 10

Regex basics: Pattern and Matcher

A regular expression (regex) is a small pattern language for describing shapes of text: "ten digits," "a word followed by a number," "anything between two quotes." java.util.regex.Pattern compiles the pattern once; Matcher applies it to one piece of text. Think of a security guard's checklist for a vehicle pass: the guard doesn't read the whole number plate by eye each time — they check it against a known shape ("two letters, two digits, two letters, four digits") and reject anything that doesn't fit, instantly.

Pattern phonePattern = Pattern.compile("^(\\+91[- ]?)?[6-9]\\d{9}$");
boolean valid = phonePattern.matcher("+91 9876543210").matches();
Method Answers Checks
matcher(text).matches() does the whole string fit the pattern? strict validation (a phone number, a PIN)
matcher(text).find() is the pattern anywhere in the string? scanning a longer string (a log line) for something
(?<name>...) a named group, read back with matcher.group("name") pulling specific fields out of matched text
text.replaceAll(pattern, replacement) the text with every match swapped out masking, cleaning
text.split(pattern) the text cut at every match parsing a delimited line
$ javac RegexBasicsDemo.java
$ java RegexBasicsDemo
-- phone number validation --
9876543210 -> valid
+91 9876543210 -> valid
+91-9876543210 -> valid
123456 -> invalid
98765432100 -> invalid

-- pulling fields out with GROUPS --
amount: 1200
name: Asha
date: 2026-11-20

-- find() vs matches(): scanning WITHIN a longer string --
order id found: 1043
matches() on the whole line: false

-- replaceAll(): masking a PIN code to its state prefix --
Deliver to pincode 41****, backup pincode 11****

-- split(): breaking a CSV-ish line on comma OR semicolon --
[Pune, 1200, Delhi, 540, Chennai, 2550]

98765432100 (11 digits) fails because ^ and $ anchor the pattern to the whole string — without them, the pattern would happily match the first 10 digits and call it valid, which is exactly the kind of quiet bug anchors exist to prevent. find() on the log line succeeds because it only needs the pattern somewhere in the text; matches() on the same line and pattern fails because the full line is far more than just order 1043.

🔍 Going deeper: regex is the wrong tool for anything with real nesting (balanced brackets, a programming language, a general JSON document) — section 6 shows exactly where that line is. It is the right tool for a fixed, flat shape: phone numbers, pincodes, log line fields, simple CSV.

Full program: examples/RegexBasicsDemo.java.

Done here? The practice set for Part 11 — including the solutions — is on the part page.

Search the guide