简体   繁体   中英

Need regular expressions for username and password

I need help with two regular expressions (ASP.NET MVC 2 app). This is what I need:

Username:

  • must contain at least one letter; digits are allowed but not required
  • cannot contain spaces
  • no special characters are allowed, such as ~!@#$%^&
  • underscore and "." (dot) is allowed
  • cannot start with a space or underscore

Password:

  • must contain at least one letter and one number
  • cannot contain spaces
  • are case sensitive

I tried with [a-zA-Z0-9]+[\w.] [a-zA-Z]+[\w.] for username but it failed for "a123456"

Regex for username:

^[a-zA-Z]\w+|[0-9][0-9_]*[a-zA-Z]+\w*$

another regex for username, look ahead is used..

^(?=.*[a-zA-Z].*)[a-zA-Z0-9]\w*$

Paolo's regex for password is okay, but you should put ^ to the begining and $ to the end of the regex to specify begining and end of the capture..

UPDATE:

it is stated that username can contain dot character also. I have modified the regex, but I have assumed that username can not start dot character also. here is the modified regex;

^([a-zA-Z][\w.]+|[0-9][0-9_.]*[a-zA-Z]+[\w.]*)$

also you might build it here

http://gskinner.com/RegExr/

Thanks to Gursel , this regex should do for the username:

([a-zA-Z\d]+[\w\d]*|)[a-zA-Z]+[\w\d.]*

( Regexr here )

and this for the password:

([a-zA-Z]+[\d]+|[\d]+[a-zA-Z]+)[^\s]*

( Regexr here ).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM