Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex to match anything but two words

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.

like image 260
goombaloon Avatar asked Jul 26 '11 13:07

goombaloon


People also ask

How do you exclude a word in regex?

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.

How do you regex multiple words?

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.

What does '$' mean in regex?

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.

What is a word boundary regex?

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.


1 Answers

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.

like image 154
Tim Pietzcker Avatar answered Oct 08 '22 23:10

Tim Pietzcker