Search code examples
regexregex-negation

Negating a complex regex containing three parts


I need a regex which is matched when the string doesn't have both lowercase and uppercase letters.

  • If the string has only lowercase letters -> should be matched
  • If the string has only uppercase letters -> should be matched
  • If the string has only digits or special characters -> should be matched

For example

abc, ABC, 123, abc123, ABC123&^ - should match

AbC, A12b, AB^%12c - should not match

Basically I need an inverse/negation of the following regex:

^(?=.*[a-z])(?=.*[A-Z]).+$


Solution

  • Does not sound like any lookarounds would be needed.

    Either match only characters that are not a-z or only characters, that are not A-Z.

    ^(?:[^a-z]+|[^A-Z]+)$
    

    See this demo at regex101 (used + for one or more)