Regex matching and groups
What you will learn
A regular expression describes a pattern of text. Compile a reusable Pattern, then create a Matcher for each input. A complete match validates the entire region; a search finds matching pieces within it. Capturing groups make selected parts available without manually slicing strings.
- Distinguish matches, lookingAt and find.
- Extract named and optional groups from short strings.
- Choose ASCII or Unicode matching deliberately.
Each example is a complete Main.java file. Use a fresh directory, javac --release 21 Main.java, then java Main. No external dependencies.
Validate or search
import java.util.*;import java.util.regex.*;import java.nio.*;import java.nio.charset.*;import java.io.*;import javax.xml.XMLConstants;import javax.xml.parsers.*;import org.xml.sax.*;import org.xml.sax.helpers.DefaultHandler;import org.w3c.dom.*;public class Main { public static void main(String[] args) throws Exception { var p = Pattern.compile("[A-Z]{2}-[0-9]{3}"); System.out.println(p.matcher("AB-123").matches()); System.out.println(p.matcher("AB-123 extra").matches()); System.out.println(p.matcher("AB-123 extra").lookingAt()); System.out.println(p.matcher("item AB-123").find()); }}Expected output:
truefalsetruetrueThe same pattern can validate, check a prefix, or search within a larger string.
Pattern and matcher responsibilities
Pattern is immutable and reusable across threads. Matcher carries mutable search state and is not thread-safe. A fresh matcher starts at the beginning of its region. matches() requires the entire region to fit; lookingAt() requires a prefix; find() scans for the next match. Do not query group() before a successful matching operation. start() and end() describe UTF-16 indices, with end exclusive.
Two layers of escaping
Java source strings and regex syntax both interpret backslashes. A regex digit class is written as "\\d" in a Java source literal. Use [0-9] for an explicitly ASCII business identifier. Parentheses capture unless marked (?:...); group 0 means the whole match. A group that did not participate returns null, while a participating empty group returns an empty string. Named groups use (?<name>...).
Unicode choices
By default predefined classes such as digit and word classes use ASCII-oriented definitions; UNICODE_CHARACTER_CLASS enables Unicode definitions. Explicit properties such as \p{L} describe letters. Case-insensitive ASCII matching and Unicode case folding are distinct; combine CASE_INSENSITIVE with UNICODE_CASE for Unicode-aware case matching. These choices do not normalize canonically equivalent spellings or decide what a user-visible grapheme is. Limit input length before any match.
Read named groups and positions
import java.util.*;import java.util.regex.*;import java.nio.*;import java.nio.charset.*;import java.io.*;import javax.xml.XMLConstants;import javax.xml.parsers.*;import org.xml.sax.*;import org.xml.sax.helpers.DefaultHandler;import org.w3c.dom.*;public class Main { public static void main(String[] args) throws Exception { var m = Pattern.compile("(?<code>[A-Z]{2})-(?<qty>[0-9]{1,3})").matcher("AB-12 CD-3"); while (m.find()) { System.out.println(m.group("code") + ":" + m.group("qty") + " @" + m.start() + ".." + m.end()); } }}Expected output:
AB:12 @0..5CD:3 @6..10Repeated find resumes scanning; group names avoid fragile numeric indexes.
Optional group versus empty capture
import java.util.*;import java.util.regex.*;import java.nio.*;import java.nio.charset.*;import java.io.*;import javax.xml.XMLConstants;import javax.xml.parsers.*;import org.xml.sax.*;import org.xml.sax.helpers.DefaultHandler;import org.w3c.dom.*;public class Main { public static void main(String[] args) throws Exception { var m = Pattern.compile("([A-Z]+)(?:-([0-9]+))?()").matcher("BOOK"); if (m.matches()) { System.out.println(m.group(0)); System.out.println(m.group(2) == null); System.out.println(m.group(3).isEmpty()); } }}Expected output:
BOOKtruetrueThe optional digits never participate, while the final empty capturing group does.
Unicode digit and letter policy
import java.util.*;import java.util.regex.*;import java.nio.*;import java.nio.charset.*;import java.io.*;import javax.xml.XMLConstants;import javax.xml.parsers.*;import org.xml.sax.*;import org.xml.sax.helpers.DefaultHandler;import org.w3c.dom.*;public class Main { public static void main(String[] args) throws Exception { String digits = "12"; System.out.println(Pattern.compile("\\d+").matcher(digits).matches()); System.out.println(Pattern.compile("\\d+", Pattern.UNICODE_CHARACTER_CLASS).matcher(digits).matches()); System.out.println(Pattern.compile("\\p{L}+").matcher("café").matches()); }}Expected output:
falsetruetrueThe explicit flag broadens the digit policy; the letter property accepts the accented letter.
Common mistakes
Do not use find() for whole-field validation; a valid substring may hide extra text. Do not call group() after a failed match. Avoid treating ASCII identifier rules as universal human-name validation.
Practice
For the bounded input SKU-42 SKU-7, extract both numeric quantities with find and print their sum. Reject input longer than 64 UTF-16 units before scanning.
Expected output:
49Compare your answer with the manual practice criteria.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Regex matching and groups — knowledge check
Original regex, text and structured data questions. Java 21-compatible scope.
Which method validates the whole region?
What does find do?
What does group(0) contain?
What is an unmatched optional group?
Which flag changes predefined digit classes to Unicode definitions?