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

Positive Lookahead Syntax: (?=...)

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

Positive Lookahead Syntax: (?=...)

What You'll Learn

You'll learn how to use positive lookahead to verify that a pattern exists ahead in the string without consuming it in your match.

The Core Idea

A positive lookahead is a zero-width assertion written as (?=...) that checks if a pattern follows the current position, but crucially, it doesn't include that pattern in the actual match result. Think of it like peeking ahead in a line: you can see what's coming next, but you don't step forward.

Why Use Lookahead?

Positive lookahead is perfect when you need to validate that certain conditions exist without capturing them. For example, checking that a password contains a digit somewhere, but you don't want the digit itself in your match—you want the whole password.

Syntax and Usage

The syntax is (?=pattern), where pattern is any valid regex. It asserts "at this position, pattern must follow."

Pattern p = Pattern.compile("Java(?=Script)");
Matcher m = p.matcher("JavaScript");
if (m.find()) {
    System.out.println(m.group()); // Prints: "Java"
    System.out.println("Match ends at: " + m.end()); // Position 4
}

Notice how only "Java" is captured, even though "Script" must be present for the match to succeed. The lookahead verified "Script" follows but didn't consume it.

Practical Example

Validating that a string contains a digit somewhere:

Pattern p = Pattern.compile("^(?=.*\\d).+$");
Matcher m = p.matcher("abc123");
System.out.println(m.matches()); // true - digit exists, whole string matched

The (?=.*\\d) asserts "somewhere ahead, there's a digit," but then .+ actually captures the content.

Key Takeaway: Positive lookahead (?=...) verifies a pattern exists ahead without including it in the match—essential for validation logic where you check conditions without consuming characters.