2013-03-05 119 views
1

我需要知道的正则表达式是如何对下面的情况:密码验证(有字母数字和特殊){8}

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

我得到了下面的总部设在其他的正则表达式:

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

但它失败了:

qwer!234 

任何提示吗?

+1

也许这是重复的? http://stackoverflow.com/questions/5068843/password-validation-regex – 2013-03-05 20:04:54

+0

我得到这个消息,这几乎是 – 2013-03-05 20:06:05

+4

[它看起来像我当前正则表达式匹配“qwer!234”](http:// www.rubular.com/r/aqTg4DiatS) – 2013-03-05 20:06:05

回答

0

对于所有这些特殊字符,中等程度可能是因为您没有正确地转义所有内容。

你说的Java对吗?这将打印true

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

但是,这是一个相当简单一点:

String regex = "(?=.*?\\d)(?=.*?[a-zA-Z])(?=.*?[^\\w]).{8,}"; 
+0

这没有什么区别。每个lookahead从字符串开头的相同位置开始。 – 2013-03-05 20:20:49

+0

@TimPietzcker编辑。我想我在想''*(?= c)。*',但它匹配'abcd'。那么需要'*?'在哪里? – Dukeling 2013-03-05 20:33:49

+0

非常少见,例如,如果您希望字符串中有多个匹配项,并且希望避免同时匹配两个值:比较'<.*>'与'<.*?>'匹配'“”'。 – 2013-03-05 20:35:44

1

为什么把这一切都在一个单一的正则表达式?只需为每个检查制定单独的功能,并且您的代码将更容易理解和维护。

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

您的业务逻辑是即刻可以实现的。另外,当你想添加其他条件时,你不必修改棘手的正则表达式。

+0

我不想在一堆ifs中检查它,一个正则表达式很酷:p – 2013-03-05 20:49:33

+1

@MarcosVasconcelos:“cool”并不总是最好的解决方案。当你获得程序员的经验时,你会意识到清晰度更重要。如果你采用了这个更简单的解决方案,那么你就已经完成了,并且已经在开发一些比密码验证更有趣的工作。 – 2013-03-05 20:52:52

+0

是的..当我获得了我的经验,我意识到正则表达式总是很酷和清晰(与正确的文档)里面的代码 – 2013-03-05 20:59:28

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 
+0

我已经添加了双反斜杠,!\ w工作像一个魅力:) – 2013-03-05 20:49:07

0
Pattern letter = Pattern.compile("[a-zA-z]"); 
Pattern digit = Pattern.compile("[0-9]"); 
Pattern special = Pattern.compile ("[[email protected]#$%&*()_+=|<>?{}\\[\\]~-]"); 
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(); 
} 

它将作品。