Java-Negative Lookahead

Negative Lookahead

Negative lookahead is usually useful if we want to match something not followed by something else. We can make our own negative lookaheads with the lookahead operator (?!). For example, to match all characters not followed by a digit, we could use :

 

More Examples

4

 

Negative Lookahead Before the Match Examples

2
22

 

Negative Lookahead Before and After the Match Example

 

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("[0-9]{2}(?!Fail)");

        Matcher mat = pat.matcher("20Fail 30Fail 40Pass 50Pass");
        
        while(mat.find())
        {
            System.out.println(mat.group());
        }
    }
}

Leave a Comment