Search code examples
regexregex-lookarounds

How to test if a string doesn't contain BOTH of two given substrings?


I need to provide a regex that only accepts strings that do not have both of the following two substrings: "string1", "string2". That is, if it has neither string, or if it has only one of them, it should be a match.

Note, this is NOT a duplicate of regex-for-a-string-to-not-contain-two-different-strings, which asks for regex which rejects strings if either of two substrings are found whereas I need a solution that rejects strings only when both of two substrings are present.

I've tried:

(?!=.*?(string1))(?!=.*?(string2))
^(?!.*(?=string1)(?=string2)).*$
^(?!.*(string1&string2)).*$
^((?!string1&&string2).)*$

The correct solution should find matches with (i.e., accept) the following strings:

abcd
string1
abcd,string1
string1,abcd
abcd,string2
string2,abcd

But should find no matches for (i.e., reject) the following:

string1,string2
string2,string1
string1,abcd,string2
string2,abcd,string1

Thank you!


Solution

  • You may use the following pattern:

    ^(?:(?!.*string1)|(?!.*string2)).+$
    

    Demo.

    Breakdown:

    • ^ Start of string.
    • (?: Start of a non-capturing group.
      • (?!.*string1) Ensure that "string1" doesn't exist.
      • | OR...
      • (?!.*string2) ..that "string2" doesn't exist.
    • ) Close the non-capturing group.
    • .+ Match one or more characters.
    • $ End of the string.