Course contentsShow
← Java
Lesson 2305 of 2,87044. Regular ExpressionsFree lesson

Positive Lookbehind Syntax: (?<=...)

Master positive lookbehind to assert that a pattern precedes the current position without including it in the match.

Positive Lookbehind Syntax: (?<=...)

You'll learn how to assert that specific text must appear before your match, without including that text in the result.

The Core Idea

A positive lookbehind is a zero-width assertion that checks whether a certain pattern exists immediately before the current position in the string. It says "only match here if what comes before is X" — but X itself doesn't become part of the match.

Think of it like a security checkpoint: you can only proceed if you show the right credential, but the credential itself doesn't come with you through the gate.

The Syntax

The positive lookbehind uses (?<=...) where ... is the pattern that must precede your actual match.

Pattern pattern = Pattern.compile("(?<=@)\\w+");
Matcher matcher = pattern.matcher("Contact: @john and @jane");

while (matcher.find()) {
    System.out.println(matcher.group()); // "john", then "jane"
}

Here, (?<=@) asserts "there must be an @ sign before this position," but the @ itself isn't captured. Only the word characters after it are matched.

Why Use Lookbehind?

It's perfect when you need to extract content that follows a specific marker but don't want that marker in your results:

Pattern pattern = Pattern.compile("(?<=\\$)\\d+\\.\\d{2}");
Matcher matcher = pattern.matcher("Total: $45.99 and $12.50");

while (matcher.find()) {
    System.out.println(matcher.group()); // "45.99", then "12.50"
}

The dollar signs are required context but aren't part of the prices we're extracting.

Key Takeaway: Positive lookbehind (?<=...) requires a pattern to exist immediately before the match position without including it in the captured result — perfect for context-sensitive extraction.