【问题标题】:Java Regex to not allow String Special CharactersJava 正则表达式不允许字符串特殊字符
【发布时间】:2017-08-15 12:41:11
【问题描述】:

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

-_\

而我的正则表达式如下

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

如果我找到 -_\ 正则表达式,则字符串中的任何位置都不应该匹配。 在java中使用Apache api匹配模式

【问题讨论】:

  • 最好是白名单而不是黑名单见stackoverflow.com/questions/756567/…
  • 除了剩下的三个字符之外,所有字符都需要在键盘中,所以这就是我选择黑名单的原因

标签: java regex validation passwords pattern-matching


【解决方案1】:

这是一个您可以尝试的通用正则表达式:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-10-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多