1

我需要知道以下情况的正则表达式:

  • 至少 8 个字符( ... ).{8,}
  • 有字母(?=.*[a-z|A-Z])
  • 有数字(?=.*\d)
  • 有特殊字符(?=.*[~'!@#$%?\\\/&*\]|\[=()}"{+_:;,.><'-])

我在其他正则表达式中得到了以下内容:

((?=.*\d)(?=.*[a-z|A-Z])(?=.*[~'!@#$%?\\\/&*\]|\[=()}"{+_:;,.><'-])).{8,}

但它失败了:

qwer!234

有小费吗?

4

4 回答 4

4

在 Java 正则表达式中,由于字符串转义规则,您需要将反斜杠加倍:

Pattern regex = Pattern.compile("^(?=.*\\d)(?=.*[a-zA-Z])(?!\\w*$).{8,}");

应该管用。

解释:

^              # Start of string
(?=.*\d)       # Assert presence of at least one digit
(?=.*[a-zA-Z]) # Assert presence of at least one ASCII letter
(?!\w*$)       # Assert that the entire string doesn't contain only alnums
.{8,}          # Match 8 or more characters
于 2013-03-05T20:26:01.780 回答
1

对于所有这些特殊字符,您很可能没有正确地转义所有内容。

你说Java对吗?这打印true

String regex = "((?=.*\\d)(?=.*[a-zA-Z])(?=.*[~'!@#$%?\\\\/&*\\]|\\[=()}\"{+_:;,.><'-])).{8,}";
System.out.println("qwer!234".matches(regex));

但这要简单得多:

String regex = "(?=.*?\\d)(?=.*?[a-zA-Z])(?=.*?[^\\w]).{8,}";
于 2013-03-05T20:20:14.120 回答
1

为什么要把这一切都放在一个正则表达式中?只需为每个检查创建单独的函数,您的代码就会更容易理解和维护。

if len(password) > 8 &&
   has_alpha(password) &&
   has_digit(password) &&
    ...

您的业​​务逻辑是立即可以理解的。另外,当您想添加一些其他条件时,您不必修改棘手的正则表达式。

于 2013-03-05T20:25:27.887 回答
0
Pattern letter = Pattern.compile("[a-zA-z]");  
Pattern digit = Pattern.compile("[0-9]");  
Pattern special = Pattern.compile ("[!@#$%&*()_+=|<>?{}\\[\\]~-]");  
Pattern eight = Pattern.compile (".{8}");  
...  
public final boolean ok(String password) {  
   Matcher hasLetter = letter.matcher(password);  
   Matcher hasDigit = digit.matcher(password);  
   Matcher hasSpecial = special.matcher(password);  
   Matcher hasEight = eight.matcher(password);  
   return hasLetter.find() && hasDigit.find() && hasSpecial.find()  
      && hasEight.matches();  
}  

它会起作用。

于 2013-07-04T05:43:46.350 回答