密码验证使用 Java 正则表达式失败。

huangapple go评论69阅读模式
英文:

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,}$

RegEx Demo

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

huangapple
  • 本文由 发表于 2020年5月2日 13:13:31
  • 转载请务必保留本文链接:https://go.coder-hub.com/61554792.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定