I am having troubles understanding how to use regex so that it will match everything but a string provided. I've tried using the negate operand ?!
such as (?!red|green|blue)
however that does not seem to work either.
Say I have a string that looks like this:
red blue green purple
and I want to negative match on green
so that my resulting match would be:
red blue purple
How could I achieve this?
You were on the right track with (?! ... )
, but you have to keep in mind that this is a negative lookahead, not just a negation operator. That means it verifies that the text after the current position does not match the pattern in your lookahead, and if so, it fails the match at that position. It does not match anything in and of itself. You still have to build a pattern around it. Here is an example of how you could write such a pattern:
(^| )(?!green)[^ ]*
(^| )
Beginning of string OR literal space character(?!green)
Assert that the next characters in the string do not match "green"[^ ]*
Match everything up to the next space. We can safely do this because the lookahead will have already failed the match if it was "green".Input string:
red blue green purple
Matches:
red blue purple
Note: Looking at how you've been testing the patterns on regex101, I will point out that this pattern will match each space-delimited item as separate matches. It is not possible to match a non-continuous string in regular expressions, so this is the closest solution you will get. If you need a singular non-continuous match, you are going to need to either rework your program or use something other than regex.