我想设置一个不允许使用特定特殊字符的密码,例如
-_\
我的正则表达式如下
PatternCompiler compiler = new Perl5Compiler();
PatternMatcher matcher = new Perl5Matcher();
pattern = compiler.compile("^(?=.*?[a-zA-Z])(?=.*?[0-9])([A-Za-z0-9-/-~][^\\\\\\\\_\-]*)$");
它正在部分工作。如果我在字符串和字符串开头之间放置不需要的特殊字符,它仍然与密码匹配
P@ssword123 --correct
-password@123 --it should not match
-passowrd"11 --it should not match
\password123 --it should not match
_@111Password --it should not match
p@sswor"123 --correct
如果我找到 -_\正则表达式,则字符串中的任何位置都不应匹配。 使用 Apache api 在 java 中匹配模式
最佳答案
这是您可以尝试的通用正则表达式:
^((?=[A-Za-z])(?![_\-]).)*$
^^ whitelist ^^ blacklist
您可以包含正向和负向前瞻断言,以检查字符类是否存在。类似以下内容可能适合您:
String password = "-passw@rd";
// nice trick: by placing hyphen at the end of the character class,
// we don't need to escape it
String pattern = "^((?=[A-Za-z0-9@])(?![_\\\\-]).)*$";
if (password.matches(pattern)) {
System.out.println("valid");
}
else {
System.out.println("not valid");
}
话虽这么说,我强烈建议您搜索密码的正则表达式。这是一个众所周知的老问题,在这个领域已经做了很多很好的工作,包括 Stack Overflow。
关于Java 正则表达式不允许字符串特殊字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42967934/