Home > Mobile >  RegEx: allow 1-25 letters or spaces but exclude three-letter-value-list
RegEx: allow 1-25 letters or spaces but exclude three-letter-value-list

Time:10-14

I'm new to this forum and hope someone can support me.

I need to create a RegEx pattern which allows 1 to 25 letters or spaces but does not allow one of the values EMP, NDB, POI or CWR.

I tried the following using negative lookahead:

((?!EMP|NDB|POI|CWR)[A-Za-z\s]{1,25})$

However this does not work properly, the value (like EMP) is still accepted - see https://regex101.com/r/YfflBi/1

This only works fine if I only have letters (no spaces) and limit down to 3:

((?!EMP|NDB|POI|CWR)[A-Za-z]{3})$

(see https://regex101.com/r/SzmuwP/1)

However the challenge here is that I need 1 to 25 letters or spaces to be accepted but not one of the three-letter-values I mentioned.

Many thanks in advance to everyone thinking about a solution!

CodePudding user response:

You can use

^(?:(?!EMP|NDB|POI|CWR)[A-Za-z\s]){1,25}$

See the regex demo. Details:

  • ^ - start of string
  • (?: - start of a non-capturing group:
    • (?!EMP|NDB|POI|CWR)[A-Za-z\s] - a letter or whitespace that is not the starting char of the char sequences defined in the negative lookahead
  • ){1,25} - repeat the pattern sequence inside the non-capturing group one to 25 times
  • $ - end of string.
  • Related