I need a regex to test a users password for the following:
Must be minimum 8 characters with alphanumeric format, no more than 4 consecutive numbers, no id in the password (i.e. cannot use: 1234
, 9876
, abcd
, or 1234abvc
)
I am using ^([a-zA-Z0-9!@#$*%]{8,1开发者_开发百科5})$
currently and it works great, but doesn't account for the consecutive characters piece. I'm not sure how to add that to the mix.
Any help would be great!
It would be far easier to use multiple regular expressions that implement a specific rule than to meld them all into one string.
With that in mind, the consecutives would fail with this sort of regex:
"[a-zA-Z]{4}"
or
"\d{4}"
I can't speak for everyone, but I would prefer to see this instead of a regex:
bool IsAcceptedPassword(string password, string id)
{
if (password.Contains(id)) {
return false;
}
if (password.Length < 8) {
return false;
}
// Adjust allowed characters here
const string allowedChars = "abcdefghijklmnopqrstuvwxyz0123456789@#$*%";
const string restrictRunsOf = "0123456789";
const int MaxRunLength = 4;
int currentRunLength = 0;
foreach(var ch in password) {
if (allowedChars.IndexOf(ch) == -1) {
return false;
}
if (restrictRunsOf.IndexOf(ch) == -1) {
currentRunLength = 0;
}
else if(++currentRunLength > MaxRunLength) {
return false;
}
}
return true;
}
If you want to let the caller know why the password is not accepted, you can return an enum
type or throw exceptions. I 'd prefer the enum
approach.
Easily done with a (commented) regex:
if (Regex.IsMatch(subjectString,
@"# Password: 8-15 alphanums but no more than 3 consecutive digits.
\A # Anchor to start of string.
(?!.*?[0-9]{4}) # No more than three consecutive digits.
[a-zA-Z0-9!@#$*%]{8,15} # Match from 8 to 15 alphanum chars.
\Z # Anchor to end of string.
",
RegexOptions.IgnorePatternWhitespace)) {
// Successful match
} else {
// Match attempt failed
}
If you want to solve it with regex, just add an negative lookahead assertion. You can test it here
^(?!.*\d{4,}.*)([a-zA-Z0-9!@#$*%]{8,})$
The added part (?!.*\d{4,}.*)
does not consume your string, it just checks if there are 4 or more numbers in a row and if so, its false.
Why do you want to limit the passwords to 15 characters? I removed this in my example.
精彩评论