英文:
Password validation using Java regex fails
问题
我的要求包括验证密码输入,确保以下特殊字符仅出现一次:!@#$%^&*()_+=?~
为了实现这一目标,我编写了以下代码:
StringBuilder builder = new StringBuilder("^(?!.*(.).*\)");
builder.append("(?=.*[a-z])");
builder.append("(?=.*[!@#$%^&*()_+=?~])");
Pattern pattern = Pattern.compile(builder.toString());
Matcher matcher = pattern.matcher(input);
if (matcher.matches()) {
return true;
}
但是,当我在单元测试中传入有效输入时,这段代码总是失败。我对正则表达式不太了解。
英文:
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.
答案1
得分: 0
你可以使用带有两个正向先行断言的这个正则表达式:
^(?=[^a-z]*[a-z])(?=[^!@#$%^&*()_+=?~]*[!@#$%^&*()_+=?~][^!@#$%^&*()_+=?~]*$).{12,}$
注意,在.matches()
方法中,开始和结束锚点在给定的正则表达式中会自动隐含。
正则表达式详情:
^
:开始(?=[^a-z]*[a-z])
:正向先行断言,确保至少有一个小写字母(?=[^!@#$%^&*()_+=?~]*[!@#$%^&*()_+=?~][^!@#$%^&*()_+=?~]*$)
:正向先行断言,确保仅有一个给定的特殊字符。.{12,}
:匹配至少12个任意字符$
:结束
英文:
You may use this regex with 2 lookahead assertions:
^(?=[^a-z]*[a-z])(?=[^!@#$%^&*()_+=?~]*[!@#$%^&*()_+=?~][^!@#$%^&*()_+=?~]*$).{12,}$
Note that in .matches()
method start & end anchors are automatically implied in a given regex.
RegEx Details:
^
: Start(?=[^a-z]*[a-z])
: Positive lookahead to make sure we have at least one lowercase letter(?=[^!@#$%^&*()_+=?~]*[!@#$%^&*()_+=?~][^!@#$%^&*()_+=?~]*$)
: Positive lookahead to make sure we have ONLY one of the given special character..{12,}
: Match min 12 of any characters$
: End
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论