Skip to content

How to match anything but two words using regex

How to match anything but two words using regex

In this post we will see javascript regular expression that will match anything but two words.


Problem

From below list we need to find all word except ‘foad’ and ‘foed’.

const str = 'foad food fold ford foed';

Lets start with simple regular expression where we will use the opening and closing square brackets of regular expression with ‘a’ and ‘e’ as below:-

str.match(/fo[ae]d/g); // Output ['foad', 'foed']

Final Solution

So we have output of the two words that we do not want. Now we can simply add a ‘^’ char at the start of ‘ae’ which will negate the current output. So out new expression will be:-

str.match(/fo[^ae]d/g); // Output ['food', 'fold', 'ford']

Conclusion

Hope you like the short explanation on how we can use a regular expression that will match anything but two words. See you in my next post. Till then enjoy coding 🙂

Further Reading

Javascript regex

How to find all string between two characters using Javascript regex

Please share