Java-Lookahead

Lookahead

A lookahead is a pattern that is required to match next in the string, but is not consumed by the regex engine. When a lookahead pattern succeeds, the pattern moves on, and the characters are left in the stream for the next part of the pattern to use. If the lookahead fails, the match fails (or it backtracks and tries a different approach). We can make our own lookaheads with the lookahead operator (?=). For example, to match the letter Z at the end of a word, we could use:

Here the regex engine requires the \\w\\s pattern to match but not consume the characters, leaving them for the next part of the pattern. This effectively allows us to write overlapping patterns. For instance, we can match the word “Ind” only when it’s part of the word “India,” like so:

 

More Examples

 

Nested Lookahead Example

 

Lookahead After the Match Examples

1 2 3

6

 

Lookahead Before and After the Match Example

 

A more complex example is password validation. Let’s say we want to ensure that a password is made at least 8 alphanumeric characters, and at least two numbers, in any position. We will need to use a look-ahead expression in order to enforce a requirement of two numbers. Following look-ahead expression will require any number of characters(zero or more) to be followed by a single digit, followed by any number of characters(zero or more), and another single digit.

Program

Program Source

import java.util.regex.Pattern;
import java.util.regex.Matcher;

public class Javaapp {
  
    public static void main(String[] args) {
        
        Pattern pat = Pattern.compile("(?=[a-zA-Z]*[0-9][a-zA-Z]*[0-9])[a-zA-Z0-9]{8}");
        
        Matcher mat = pat.matcher("aDa3sd4s 2sdsd3HJ FtF6FKsH fGf34sDs sdsd2sds 4FjkYGk7");
        
        while(mat.find())
        {
            System.out.println("Password : "+mat.group());
        }
    }
}

Leave a Comment