Java Regex不允许字符串特殊字符

时间:2017-03-23 05:28:54

标签: java regex validation passwords pattern-matching

我想设置一个不允许特定字符的密码,例如

-_\

我的正则表达式如下

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中的模式

1 个答案:

答案 0 :(得分:3)

以下是您可以尝试的一般正则表达式:

^((?=[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。

相关问题