Combining Lookahead and Lookbehind
You'll learn how to use multiple zero-width assertions together to create powerful patterns that match text based on what comes before and after it.
The Core Idea
Lookahead and lookbehind assertions don't consume characters—they simply check conditions. When you combine them, you create a "window" that ensures text matches only when it sits between specific boundaries, without including those boundaries in the match itself.
Think of it like finding a word in a sentence, but only if it's sandwiched between specific punctuation marks—you want the word, not the punctuation.
How to Combine Them
Place both assertions around your main pattern:
// Match digits only when preceded by "$" and followed by a space
Pattern p = Pattern.compile("(?<=\\$)\\d+(?= )");
Matcher m = p.matcher("Price: $50 or $75 today");
while (m.find()) {
System.out.println(m.group()); // Prints: 50
}
// Note: "75" doesn't match because no space follows it
Multiple Assertions
You can stack multiple lookaheads or lookbehinds:
// Match words that come after "@" but NOT before ".com"
Pattern p = Pattern.compile("(?<=@)\\w+(?!\\.)");
Matcher m = p.matcher("email@domain.com or @username");
while (m.find()) {
System.out.println(m.group()); // Prints: username
}
// "domain" doesn't match due to the negative lookahead
Real-World Example: Extracting Values
// Match numbers between "[" and "]" without capturing brackets
Pattern p = Pattern.compile("(?<=\\[)\\d+(?=\\])");
Matcher m = p.matcher("IDs: [101] [202] [303]");
while (m.find()) {
System.out.println(m.group()); // Prints: 101, 202, 303
}
Key Takeaway: Combining lookahead and lookbehind lets you precisely target text based on its surrounding context while keeping your matches clean and boundary-free—perfect for extracting data from structured formats.