Skip to main content

Working with Regular Expressions

1. Understanding Pattern Class

MethodUse
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

MethodUse
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])

ClassMatch
[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)

TokenMatch
.Any char (except newline by default)
\d / \DDigit / non-digit
\w / \WWord char / non-word
\s / \SWhitespace / non-whitespace
Java escapeUse double backslash: "\\d"

5. Using Quantifiers (*, +, ?, {n}, {n,m})

QuantifierMatch 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)

AnchorPosition
^Start of input/line
$End of input/line
\bWord boundary
\BNon-word boundary
\A / \zAbsolute 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"));
}
FormUse
(...)Capturing group
(?:...)Non-capturing
(?<name>...)Named group
\1 / \k<name>Backreference

8. Using Alternation (|)

PatternMatch
cat|dog|birdAny of three
(cat|dog) foodGroup + alternation

9. Replacing Text

MethodUse
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

MethodDetail
str.split(re)Trailing empty strings dropped
str.split(re, -1)Keep trailing empties
pattern.splitAsStream(s)Stream of parts

11. Using Flags

FlagEffect
CASE_INSENSITIVEIgnore case
MULTILINE^/$ match line boundaries
DOTALL. matches newlines
UNICODE_CASEUnicode-aware case
COMMENTSWhitespace + # comments allowed
Inline(?i), (?m), (?s)

12. Understanding Greedy vs Reluctant vs Possessive

QuantifierBehavior
X*Greedy (longest match)
X*?Reluctant (shortest match)
X*+Possessive (no backtracking)

Was this article helpful?