Regular Expression - Exclude list of words for a name

11,655

Solution 1

Try something like this:

^(?!static$|my$|admin$|www$).*$

This will disallow "static" but allow "statice", "statica", etc. By anchoring each blacklisted word to the end of the string you will only match them if they are standing alone without any trailing characters.

Edit: codeaddict has suggested a cleaner way to do basically the same thing:

^(?!(?:static|my|admin|www)$).*$

Solution 2

I'll answer my question to give the right answer to my question (a regexp that include both obligations), but I'll give the accepted answer to Andrew Hare that lead me to the correct way :)

Here's how to :

  • Allow only a-z, 0-9, _ chars, with a minimum length of 3
  • Exclude admin, static, my and www

Here is the regexp :

^(?!static$|my$|admin$|www$)[a-z0-9\_]{3,}$

Or, as Codaddict mentionned it, with a single end anchor :

^(?!(?:static|my|admin|www)$)[a-z0-9\_]{3,}$

Hope this helps in the future!

Share:
11,655
Cyril N.
Author by

Cyril N.

I build, launch and grow products. Working full-time on PDFShift and ImprovMX. Recently sold VoilaNorbert, Transferslot and Selldom

Updated on June 28, 2022

Comments

  • Cyril N.
    Cyril N. almost 2 years

    I'm trying to make a regular expression that accepts this:

    • Only a-z, 0-9, _ chars, with a minimum length of 3
    • admin, static, my and www are rejected.

    For the first part, I already managed to do it with :

    ^[a-zA-Z0-9\\_]{3,}$
    

    But I don't know how to exclude the words listed previously.

    For example, that would mean :

    • static is not allowed (of course), but
    • statice is allowed
    • estatic is allowed

    Using this regular expression :

    ^(?!static|my|admin|www).*$
    

    doesn't work well : it excludes statice (and everything after the unauthorized word).

    Do you know which regular expression will fit my need?

    • eldarerathis
      eldarerathis about 13 years
      What language is this? To be honest, some kind of simple string comparison might be easier for the latter part. I.e. just a simple if (userName != "admin" && userName != "static" && ... ) (or whatever the proper operator is for the particular language in question).
    • Cyril N.
      Cyril N. about 13 years
      It would be in Java, to be precise, in the @Match validation system of the Play! Framework.
  • codaddict
    codaddict about 13 years
    +1, or use a single end anchor: ^(?!(?:static|my|admin|www)$).*$