I want a regular expression to check that
a password must be eight characters including one uppercase letter, one special character and alphanumeric characters.
And here is my validation expression which is for eight characters including one uppercase letter, one lowercase letter, and one number or special character.
(?=^.{8,}$)((?=.*\d)|(?=.*\W+))(?![.\n])(?=.*[A-Z])(?=.*[a-z]).*$"
How I can write it for a password that must be eight characters including one uppercase letter, one special character and alphanumeric characters?
To match a character having special meaning in regex, you need to use a escape sequence prefix with a backslash ( \ ). E.g., \. matches "." ; regex \+ matches "+" ; and regex \( matches "(" . You also need to use regex \\ to match "\" (back-slash).
?= is a positive lookahead, a type of zero-width assertion. What it's saying is that the captured match must be followed by whatever is within the parentheses but that part isn't captured. Your example means the match needs to be followed by zero or more characters and then a digit (but again that part isn't captured).
The regular expression you are after will most likely be huge and a nightmare to maintain especially for people who are not that familiar with regular expressions.
I think it would be easier to break your regex down and do it one bit at a time. It might take a bit more to do, but I am pretty sure that maintaining it and debugging it would be easier. This would also allow you to provide more directed error messages to your users (other than just Invalid Password
) which should improve user experience.
From what I am seeing you are pretty fluent in regex, so I would presume that giving you the regular expressions to do what you need would be futile.
Seeing your comment, this is how I would go about it:
Must be eight characters Long: You do not need a regex for this. Using the .Length
property should be enough.
Including one uppercase letter: You can use the [A-Z]+
regular expression. If the string contains at least one upper case letter, this regular expression will yield true
.
One special character: You can use either the \W
which will match any character which is not a letter or a number or else, you can use something like so [!@#]
to specify a custom list of special characters. Note though that characters such as $
, ^
, (
and )
are special characters in the regular expression language, so they need to be escaped like so: \$
. So in short, you might use the \W
.
Alphanumeric characters: Using the \w+
should match any letter and number and underscore.
Take a look at this tutorial for more information.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With