Working with Regular Expressions
1. Understanding Pattern Class
| Method | Use |
|---|---|
Pattern.compile(re) | Compile pattern |
Pattern.compile(re, flags) | With flags |
p.matcher(input) | Matcher for input |
p.split(input) | Split using pattern |
Pattern.quote(literal) | Escape for literal match |
2. Understanding Matcher Class
| Method | Use |
|---|---|
matches() | Full-string match |
find() | Next sub-match |
group() / group(n) / group(name) | Match content |
start() / end() | Match positions |
replaceAll(repl) / replaceFirst(repl) | Substitution |
results() JAVA 9+ | Stream of MatchResult |
3. Using Character Classes ([abc], [^abc], [a-z])
| Class | Match |
|---|---|
[abc] | One of a, b, or c |
[^abc] | Anything except |
[a-zA-Z0-9] | Range |
[a-z&&[^bc]] | Intersection (a-z but not b or c) |
4. Using Predefined Classes (\d, \w, \s)
| Token | Match |
|---|---|
. | Any char (except newline by default) |
\d / \D | Digit / non-digit |
\w / \W | Word char / non-word |
\s / \S | Whitespace / non-whitespace |
| Java escape | Use double backslash: "\\d" |
5. Using Quantifiers (*, +, ?, {n}, {n,m})
| Quantifier | Match Count |
|---|---|
* | 0 or more |
+ | 1 or more |
? | 0 or 1 |
{n} | Exactly n |
{n,} | n or more |
{n,m} | Between n and m |
6. Using Anchors (^, $, \b, \B)
| Anchor | Position |
|---|---|
^ | Start of input/line |
$ | End of input/line |
\b | Word boundary |
\B | Non-word boundary |
\A / \z | Absolute start/end |
7. Using Grouping and Capturing
Example: Named groups
Pattern p = Pattern.compile("(?<y>\\d{4})-(?<m>\\d{2})-(?<d>\\d{2})");
Matcher m = p.matcher("2026-05-12");
if (m.matches()) {
int year = Integer.parseInt(m.group("y"));
}
| Form | Use |
|---|---|
(...) | Capturing group |
(?:...) | Non-capturing |
(?<name>...) | Named group |
\1 / \k<name> | Backreference |
8. Using Alternation (|)
| Pattern | Match |
|---|---|
cat|dog|bird | Any of three |
(cat|dog) food | Group + alternation |
9. Replacing Text
| Method | Use |
|---|---|
str.replaceAll(re, repl) | String shortcut |
matcher.replaceAll(repl) | From compiled pattern |
matcher.replaceAll(mr -> ...) JAVA 9+ | Function-based |
| Backref in replacement | $1, ${name} |
10. Splitting Text
| Method | Detail |
|---|---|
str.split(re) | Trailing empty strings dropped |
str.split(re, -1) | Keep trailing empties |
pattern.splitAsStream(s) | Stream of parts |
11. Using Flags
| Flag | Effect |
|---|---|
CASE_INSENSITIVE | Ignore case |
MULTILINE | ^/$ match line boundaries |
DOTALL | . matches newlines |
UNICODE_CASE | Unicode-aware case |
COMMENTS | Whitespace + # comments allowed |
| Inline | (?i), (?m), (?s) |
12. Understanding Greedy vs Reluctant vs Possessive
| Quantifier | Behavior |
|---|---|
X* | Greedy (longest match) |
X*? | Reluctant (shortest match) |
X*+ | Possessive (no backtracking) |