In this short tutorial, we are going to explain in detail how to use regex to exclude a specific string.

First, we will use a negative lookahead assertion to achieve the exclusion. Then, we will see how to ignore a group of characters using the anchor caret “^”.

Excluding String using Negative Lookahead

Typically, we can use negative lookahead to assert that a given string doesn’t contain a specific word.

Simply put, a negative lookahead is denoted by the syntax (?!expr), where expr represents the pattern we want to exclude.

For instance, let’s see how to match any word except “ABC”:

    
        public static void main(String[] args) {
            String strToExclude = "ABC";
            boolean isExcluded = Pattern.compile("^((?!" + strToExclude + ").)\*$")
                    .matcher("ABCD")
                    .matches();
            System.out.println(isExcluded); // false
        }
    

As we can see, the regex uses the negative lookahead assertion “(?!.ABC)”. It matches every string not containing the given string “ABC”.

Regex to Exclude Characters

Similarly, we can use the caret anchor ”^” as a negation operator inside brackets.

For example, if we want to match any character except “A”, “B”, and “C”, we can use [^ABC] in regular expressions.

So, let’s see how to do it in practice:

    
        public static void main(String[] args) {
            boolean doesMatch = Pattern.compile("[^ABC].*")
                    .matcher("devwithus")
                    .matches();
            System.out.println(doesMatch); // true
        }
    

Please note that the ”^” acts as an exclusion operator only if it is inside brackets. Outside of a character set, it indicates the start of a string.

Conclusion

To sum it up, we explored different ways of implementing a regex to exclude a specific string in Java.

We explained using practical examples how to achieve this using negative lookahead. Then, we saw how to exclude a group of characters using the caret anchor.