I'm trying to write a regular expression to match anything that isn't "foo" and "bar". I found how to match anything but one word at Regular expression to match a line that doesn't contain a word? but I'm not very skilled with regex and am unsure of how to add a second word to this critera.
Any help would be most appreciated!
CLARIFICATION:
I wanted to match on anything that wasn't EXACTLY foo or bar.
If you want to exclude a certain word/string in a search pattern, a good way to do this is regular expression assertion function. It is indispensable if you want to match something not followed by something else. ?= is positive lookahead and ?! is negative lookahead.
However, to recognize multiple words in any order using regex, I'd suggest the use of quantifier in regex: (\b(james|jack)\b. *){2,} . Unlike lookaround or mode modifier, this works in most regex flavours.
Literal Characters and Sequences For instance, you might need to search for a dollar sign ("$") as part of a price list, or in a computer program as part of a variable name. Since the dollar sign is a metacharacter which means "end of line" in regex, you must escape it with a backslash to use it literally.
A word boundary, in most regex dialects, is a position between \w and \W (non-word char), or at the beginning or end of a string if it begins or ends (respectively) with a word character ( [0-9A-Za-z_] ). So, in the string "-12" , it would match before the 1 or after the 2.
Answer to the question: "A Regular Expression to match anything that isn't "foo" and "bar"?"
^(?!foo$|bar$).*
would do exactly that.
^ # Start of string (?! # Assert that it's impossible to match... foo # foo, followed by $ # end of string | # bar$ # bar, followed by end of string. ) # End of negative lookahead assertion .* # Now match anything
You might need to set RegexOptions.Singleline
if your string can contain newlines that you also wish to match.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With