Conversely, when a particular string does not match a regex, we say that it’s a “not match”.

In other words, it’s a way to denote that the pattern defined by the regular expression does not appear in the input string.

Regex Not Match Given Word

Typically, we can use a negative lookahead to create a regex that does not match a specific word.

Simply put, a negative lookahead is a special construct that matches a pattern only if it is not followed by another one.

For instance, here’s a Java example of a regex that does not match the word “dev”:

    
        public static void main(String[] args) {
            String input = "Welcome to devwithus.com";
            boolean doesMatch = Pattern.compile("(?!.*dev).*")
                .matcher(input)
                .matches();
            System.out.println(doesMatch); // false
        }
    

Now, let’s break down the above pattern:

  • (?!.*dev) means do not match if the substring “dev” appears anywhere in the string

  • .* matches any characters zero or more times

String Not Containing Pattern

The easiest way to indicate that a string does not contain a pattern is using the negation symbol ^ inside brackets.

For example, [^abc] denotes that a string should NOT contain any of the characters specified in the brackets.

Let’s say that the characters we want to avoid matching are “d”, “e”, and “v”.

So, the regular expression to match any string that does not contain the above letters would be:

    
        boolean doesMatch = "dev with us".matches("[^dev]*");
        System.out.println(doesMatch); // false
    

Please bear in mind that when the anchor ^ is placed out of the brackets, it means that the regex should match the beginning of the string.

Matching All Except Specific String

Basically, we can use a negative lookahead assertion to answer our central question.

Here’s another Java example of how we can use a negative lookahead to match all strings except “devwithus”:

    
        Pattern.compile("^(?!devwithus$).*$")
               .matcher(input)
               .matches();
    

In the above regular expression, the ^ and $ anchors ensure that the pattern matches the entire string from beginning to end.

Please note that ?! means “not followed by” and $ matches the end of the string.

Conclusion

Overall, the “not match” concept in regex is useful when we need to specify patterns that should not be present in a given string.