Reputation: 18276
I need to know how the regex is for the following case:
( ... ).{8,}
(?=.*[a-z|A-Z])
(?=.*\d)
(?=.*[~'!@#$%?\\\/&*\]|\[=()}"{+_:;,.><'-])
I got the following based in other regex:
((?=.*\d)(?=.*[a-z|A-Z])(?=.*[~'!@#$%?\\\/&*\]|\[=()}"{+_:;,.><'-])).{8,}
But it fails for:
qwer!234
Any tips?
Upvotes: 1
Views: 6801
Reputation: 983
Pattern letter = Pattern.compile("[a-zA-z]");
Pattern digit = Pattern.compile("[0-9]");
Pattern special = Pattern.compile ("[!@#$%&*()_+=|<>?{}\\[\\]~-]");
Pattern eight = Pattern.compile (".{8}");
...
public final boolean ok(String password) {
Matcher hasLetter = letter.matcher(password);
Matcher hasDigit = digit.matcher(password);
Matcher hasSpecial = special.matcher(password);
Matcher hasEight = eight.matcher(password);
return hasLetter.find() && hasDigit.find() && hasSpecial.find()
&& hasEight.matches();
}
It will works.
Upvotes: 0
Reputation: 55619
With all those special characters, it's moderately likely that you didn't escape everything properly.
You said Java right? This prints true
:
String regex = "((?=.*\\d)(?=.*[a-zA-Z])(?=.*[~'!@#$%?\\\\/&*\\]|\\[=()}\"{+_:;,.><'-])).{8,}";
System.out.println("qwer!234".matches(regex));
But this is quite a bit simpler:
String regex = "(?=.*?\\d)(?=.*?[a-zA-Z])(?=.*?[^\\w]).{8,}";
Upvotes: 1
Reputation: 336378
In a Java regex, you need to double the backslashes because of string escaping rules:
Pattern regex = Pattern.compile("^(?=.*\\d)(?=.*[a-zA-Z])(?!\\w*$).{8,}");
should work.
Explanation:
^ # Start of string
(?=.*\d) # Assert presence of at least one digit
(?=.*[a-zA-Z]) # Assert presence of at least one ASCII letter
(?!\w*$) # Assert that the entire string doesn't contain only alnums
.{8,} # Match 8 or more characters
Upvotes: 4
Reputation: 386210
Why put this all in a single regular expression? Just make separate functions for each check and your code will be much easier to understand and maintain.
if len(password) > 8 &&
has_alpha(password) &&
has_digit(password) &&
...
Your business logic is instantly undertandable. Plus, you don't have to modify a tricky regular expression when you want to add some other condition.
Upvotes: 1