Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

regex for usernames

Tags:

c#

regex

I am trying to figure out how to setup a regex expression on doing the following requirements.

  • Must consist at least two characters that are alpha characters a-zA-Z
  • Must consist only ONE underscore or dash allowed anywhere AFTER the first check, the dash/underscore cannot be at the end as the same rule to apply as the first step
  • Must be alpha-numeric characters.

Basically a good example is

Acceptable Usernames

  • myusername_09
  • username-09
  • bw-09

Unacceptable Usernames

  • bw 09
  • bw--09
  • bw_-09
  • username__09

If any help would appreciate, this is what I had but its not working for me as what I want it to be.

^(?=[A-Za-z0-9])(?!.*[_-]{2})[A-Za-z0-9_-]+$
like image 440
Benjamin Avatar asked Nov 13 '10 01:11

Benjamin


People also ask

How do you validate a username in Python?

valid_username(username) # if it isn't valid we should tell them why if not(result): print (reason) # otherwise the username is good - ask them for a password # get a password from the user password = input("Password: ") # determine if the password is valid pwresult, pwreason = uservalidation.

What is the regex for email?

[a-zA-Z0-9+_. -] matches one character from the English alphabet (both cases), digits, “+”, “_”, “.” and, “-” before the @ symbol. + indicates the repetition of the above-mentioned set of characters one or more times.


1 Answers

If I understand your requirement correctly, you just need to validate that the username is correct? If so, I'd use this regex:

^[A-Za-z]{2,}[_-]?[A-Za-z0-9]{2,}$

You did not say how many characters would be required after the dash or underscore; my example requires at least 2 more after. It can be altered as needed.

EDIT: I've added the ? after the [_-] to account for that being optional, per your comment below.


Some additional information on quantifiers:

  • {N,} means that there must be at least N characters from the preceding item to match.
  • {N} means there must be exactly N of the preceding.
  • {N,M} means there must be at least N, but no more than M.
  • ? means there must be 0 or 1 of the preceding.
  • + means there must be 1 or more.
  • * means there must be 0 or more.
like image 142
Andrew Barber Avatar answered Nov 11 '22 13:11

Andrew Barber