regexjsr330

Regex on negative assertions for specific strings


What is the regex using javax.validation.constraints @Pattern for user not to be able to choose username such as "admin" or "manager"?

I am not understanding how to use "?!" to indicate word which must be excluded. Could you please suggest some examples with exclusion of just "admin" string and I will figure out the rest.


Solution

  • You can use the following expression which will match any value that is not manager or admin:

    ^(?!(admin|manager)).*$
    

    and if you want to disallow the user to choose usernames which contain manager or admin anywhere in the string like usr_admin, myManager_101, etc ..

    Then you can use the following:

    ^(?!.*?(admin|manager)).*$