2013-03-05 116 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(); 
} 

它將作品。