Вопрос

I want to check login with regex.

  1. Login must contain at least 3-16 characters ({3,16})
  2. Login can contains only alphanumeric, - and _ ([a-zA-Z0-9_-])
  3. Login can NOT contain __, --, -_, _- ((?!--|__|-_|_-))
  4. Login can NOT contain - or _ at the end. ((?!-|_))

How to combine all of expressions into one?

EDIT:
5. Login can NOT start with - or _

Это было полезно?

Решение

^(?!_|-)([a-zA-Z0-9]|[\-_](?!_|-|$)){3,16}$

Matches

-the start of the string

-checks that the first character is not _ or -

-a token that is (one alphanumerical) OR (one hyphen/underscore that is NOT followed by a hyphen/underscore/end of line)

-the above token, 3 to 16 times

-the end of the string

Другие советы

You can use positive assertions:

  • Login must contain at least 3-16 characters ({3,16})

    (?=.{3,16}$)
    
  • Login can contains only alphanumeric, - and _ ([a-zA-Z0-9_-])

    (?=[a-zA-Z0-9_-]*$)
    
  • Login can NOT contain , --, -_, - ((?!--||-|_-))

    (?!.*(?:__|--|-_|_-))
    
  • Login can NOT containn nor start with - or _

    (?![_-]|.*[_−]$)
    

Result:

^(?![_-]|.*(?:__|--|-_|_-)|.*[_-]$)[a-zA-Z0-9_-]{3,16}$
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top