[英]Password validation using Java regex fails
My requirements include among other things to validate for the password input to include one of the following characters only once.我的要求包括验证密码输入是否仅包含以下字符之一。 ?@#$%^&*()_+=?~
?@#$%^&*()_+=?~
To accomplish that I wrote the following:为了实现这一点,我写了以下内容:
StringBuilder builder = new StringBuilder("(?=.*[a-z])");
builder.append("(?=.{1}[!@#$%^&*()_+=?~])");
Pattern pattern = Pattern.compile(builder.toString());
Matcher matcher = pattern.matcher(input);
if(matcher.matches){
return True;
}
But this always fails when I pass valid input in my unit test.但是,当我在单元测试中通过有效输入时,这总是失败。 I am new to regex.
我是正则表达式的新手。
You may use this regex with 2 lookahead assertions:您可以将此正则表达式与 2 个前瞻断言一起使用:
^(?=[^a-z]*[a-z])(?=[^!@#$%^&*()_+=?~]*[!@#$%^&*()_+=?~][^!@#$%^&*()_+=?~]*$).{12,}$
Note that in .matches()
method start & end anchors are automatically implied in a given regex.请注意,在
.matches()
方法中,开始和结束锚点自动隐含在给定的正则表达式中。
RegEx Details:正则表达式详细信息:
^
: Start ^
: 开始(?=[^az]*[az])
: Positive lookahead to make sure we have at least one lowercase letter (?=[^az]*[az])
:正向前瞻以确保我们至少有一个小写字母(?=[^?@#$%^&*()_+=?~]*[?@#$%^&*()_+=?~][^!@#$%^&*()_+=?~]*$)
: Positive lookahead to make sure we have ONLY one of the given special character. (?=[^?@#$%^&*()_+=?~]*[?@#$%^&*()_+=?~][^!@#$%^&*()_+=?~]*$)
:积极的前瞻,以确保我们只有一个给定的特殊字符。.{12,}
: Match min 12 of any characters .{12,}
:匹配至少 12 个字符$
: End $
: 结束
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.