Reputation: 557
I am trying to make a regular expression that checks a field and make sure it includes (special characters or numbers) including all the other character as well. I am failing to do it correctly.
I've been using some regular expression sites like http://www.gskinner.com/RegExr/ to give me some help and make sure I'm getting the right thing, but I'm not.
The closest I've gotten is this:
(?!^[0-9]*$)(?!^[a-zA-Z!@#$%^&*()_+=<>?]*$)^([a-zA-Z!@#$%^&*()_+=<>?0-9]{6,15})$
It checks for everything although it is required that there is a number in it. But I need it to be required to have a number OR special character.
Upvotes: 0
Views: 498
Reputation: 13196
This requires a number AND a special character:
[^\s\w].*\d|\d.*[^\s\w]
This requires a number OR a special character:
\d|[^\s\w]
The pipe character '|' means OR.
This one matches an entire line if there is both a special character AND a number:
.*(:?[^\s\w].*\d|\d.*[^\s\w]).*
This one matches an entire line if there is a special character OR a number:
.*(?:\d|[^\s\w]).*
Upvotes: 1
Reputation: 23796
Special characters or numbers? Well, [^A-Za-z_ ]
is probably good enough then.
Edit:
So, if you are trying to do password validation, then this is really simple with positive lookaheads. Shameless stolen from: http://www.mkyong.com/regular-expressions/how-to-validate-password-with-regular-expression/
( # Start of group
(?=.*\d) # must contains one digit from 0-9
(?=.*[a-z]) # must contains one lowercase characters
(?=.*[A-Z]) # must contains one uppercase characters
(?=.*[@#$%]) # must contains one special symbols in the list "@#$%"
. # match anything with previous condition checking
{6,20} # length at least 6 characters and maximum of 20
)
Upvotes: 0