2013-03-13 51 views
5

我試圖創建一個正則表達式模式匹配(對於密碼)其中字符串必須是8到30個字符,必須至少有2數字,至少2個字母(不區分大小寫),至少1個特殊字符,且不包含空格。正則表達式匹配的至少2位,2個字母以任何順序在一個字符串

我有空格和特殊字符匹配的工作,但在2位和2個英文字母我得到拋出,因爲他們並不需要是連續的。

即它應該匹配a1b2c$ab12$1aab2c$

像這樣的信嗎?

(?=.*[a-zA-Z].*[a-zA-Z]) // Not sure. 

這個字符串下面的作品,但只有2個字母是連續和2號是如果字母,數字,特殊字符相互交織consecutive..it失敗。

(?=^.{8,30}$)((?=.*\\d)(?=.*[A-Za-z]{2})(?=.*[0-9]{2})(?=.*[[email protected]#$%^&*?]{1})(?!.*[\\s]))^.* 
+5

你真的確認你需要正則表達式的呢? – Scorpil 2013-03-13 18:54:48

+0

我認爲對正則表達式,只是對每一個與if語句和某種string.contains()函數單獨檢查。 gparyani給出了一個似乎比正則表達式更好的解決方案 – user1751547 2013-03-13 19:13:32

+0

它看起來像我需要正則表達式,因爲這是一個Liferay配置的一部分。 – user2166893 2013-03-13 20:14:04

回答

5

如果你不想給它們是連續(?=.*[a-zA-Z].*[a-zA-Z])是正確的做法。同樣數字(?=.*\\d.*\\d)(?=(.*\\d){2})

試試這個正則表達式

(?=^.{8,30}$)(?=(.*\\d){2})(?=(.*[A-Za-z]){2})(?=.*[[email protected]#$%^&*?])(?!.*[\\s])^.* 
+1

謝謝。這工作!正是我在找什麼。 – user2166893 2013-03-13 20:23:01

+0

很高興我能幫助:) – Pshemo 2013-03-13 20:36:11

0

我觀察你的例子,你提供的不是8到30個字符

嘗試這種模式如果你想一次8-30個字符

(?=[^\s]*[^\sa-zA-Z0-9][^\s]*)(?=[^\s]*[a-zA-Z][^\s]*[A-Za-z][^\s]*)(?=[^\s]*\d[^\s]*\d[^\s]*)[^\s]{8,30} 
1

你的猜測是相當準確的。它可以看起來更加優雅與parens。

(?=(.*[a-zA-Z]){2}) 

雖然聽起來像是在正確的軌道上。

3

使用一個循環遍歷字符串:

/** 
* Checks to see if the specified string has between 8 and 30 characters, has at least 2 digits, at least 2 letters, at least one special character, and no spaces. 
* @param s the String to be checked 
* @return s, if it passes the above test 
* @throws IllegalArgumentException if it does not 
*/ 
public static String check(String s) 
{ 
    IllegalArgumentException invalid = new IllegalArgumentException(); 
    if(s.length() < 8 || s.length() > 30) 
     throw invalid; 
    int letters = 0, numbers = 0, specialChars = 0; 
    for(char c : s.toCharArray()) 
    { 
     if(c == ' ') 
      throw invalid; 
     else if(Character.isLetter(c)) 
      ++letters; 
     else if(Character.isDigit(c)) 
      ++numbers; 
     else 
      ++specialChars; 

    } 
    if(letters < 2 || numbers < 2 || specialChars < 1) 
     throw invalid; 
    return s; 
} 
+0

使用正則表達式是更爲有效 – Barnaby 2016-02-19 12:11:14

相關問題