Practical Lookbehind: Currency and Units
You'll learn how to use lookbehind assertions to match numbers that follow currency symbols or unit labels, without including those prefixes in your captured result.
The Core Problem
Imagine you're parsing financial reports or scientific data. You want to extract numeric values like $42.50 or 5kg, but you only want the number itself—not the $ or kg. You need to ensure the symbol/unit is there (for validation), but you don't want it cluttering your match.
How Lookbehind Solves This
A positive lookbehind (?<=...) asserts that something must appear immediately before your match, but it doesn't consume those characters. Think of it like checking your rearview mirror: you verify what's behind you without actually moving backward.
For currency, you might use:
Pattern pattern = Pattern.compile("(?<=\\$)\\d+\\.\\d{2}");
Matcher matcher = pattern.matcher("Price: $19.99");
if (matcher.find()) {
System.out.println(matcher.group()); // Output: 19.99
}
Notice group() returns only 19.99, not $19.99. The (?<=\\$) verified the dollar sign exists but didn't capture it.
Units Example
For measurements like weight:
Pattern pattern = Pattern.compile("(?<=\\b)\\d+(?=kg\\b)");
Matcher matcher = pattern.matcher("Package weight: 5kg");
if (matcher.find()) {
System.out.println(matcher.group()); // Output: 5
}
Here we combine lookbehind (word boundary check) with lookahead to sandwich the number between context clues.
Multiple Currencies
You can use alternation inside lookbehind:
Pattern pattern = Pattern.compile("(?<=[$€£])\\d+\\.\\d{2}");
// Matches numbers after $, €, or £
Key Takeaway: Use positive lookbehind (?<=...) to match numbers that must follow currency symbols or unit labels, extracting clean numeric values while still validating the required prefix context.