2013-11-20 22 views
1

我需要一個正則表達式來匹配以下規則。正則表達式匹配這些規則

1. Atleast 1 numerical character. 
2. Atleast 1 of these (!, @, #, $, %, _) non-alphanumeric characters. 
3. Uppercase alphabets. 
4. Lowercase alphabets 

我試着創建一個模式如下,但東西是任何字符都可以在任何位置。我有點卡在這裏。

^[[A-Z]+[a-z]+[0-9]+[[email protected]#\\$%_]+]$ 

這些應該滿足上述每個條件。

1. [0-9]+ 
2. [[email protected]#\\$_%]+ 
3. [A-Z]+ 
4. [a-z]+ 

但是,如何將它們組合在一起,以便它們可以以任何順序出現,但每個組都會出現一次。

SOLUTION:

^(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9])(?=.*?[[email protected]#$%_])[[email protected]#$%_]*$ 
+0

[複雜的密碼正則表達式]的可能的副本(http://stackoverflow.com/questions/3466850/complex-password-regular-expression) – Toto

回答

5

您需要使用positive lookahead assertions分別獨立地檢查每一個條件:

^(?=.*[A-Z])(?=.*[a-z])(?=.*[0-9])(?=.*[[email protected]#$%_]).*$ 

將匹配包含每個這些字符中的至少一個任意字符串(但也可能包含其他字符)。

的向前看符號實際上不參加比賽(這就是爲什麼你可以將它們陸續 - 它們都被錨定在字符串的開始),但它們是否包含在其中的正則表達式可能是在當前位置匹配。

說明:

^    # Start of string. 
(?=   # Look ahead to see if it's possible to match... 
.*   # any string 
[A-Z]   # followed by one uppercase ASCII letter. 
)    # End of lookahead. 
(?=.*[a-z]) # Same for lowercase ASCII letter 
(?=.*[0-9]) # Same for ASCII digit 
(?=.*[[email protected]#$%_]) # Same for this list of "special" characters 
.*    # Now match any string. 
$    # End of string. 
+0

如果你不介意你能解釋它,我是初學者在正則表達式 –

+0

@Suganthan:在上面鏈接的教程中很好地解釋了Lookaheads。其餘的,看我的編輯。 –

+0

查看和理解正則表達式模式可能很困難(我認爲自己也是一個初學者!)我發現像[這個](http://regex101.com)這樣的網站是可視化正則表達式工作原理的好地方。從那裏你根據你使用的語言進行調整 – Jaycal

1

最簡單的解決方案是在一個單一的正則表達式不檢查一切。

import java.util.regex.Matcher; 
import java.util.regex.Pattern; 

public class RegexMatches 
{ 
    public static void main(String args[]){ 

     // String to be scanned to find the pattern. 
     String line = "S9s_3g90ae98iogw4i%%%%%%%[email protected]!89fh#453&!"; 

     if ( line.matches("\\d")   // at least one digit 
     && line.matches("[[email protected]#\\\\$_%]") // at least one special character 
     && line.matches("[a-z]")   // at least one lowercase 
     && line.matches("[A-Z]")   // at least one uppercase 
    ) { 
     System.out.println("Found value: "); 
     } else { 
     System.out.println("NO MATCH"); 
     } 
    } 
} 

你有一個圖靈完整的編程語言在您的處置。不要試圖用正則表達式來解決所有問題(就像我喜歡它們一樣)。

+0

是的,這很容易,但我的意圖是學習正則表達式,並瞭解如何使用正則表達式處理不同的情況。 :) – Adarsh

+0

那麼,一個重要的教訓是不要試圖用正則表達式來解決所有問題! :) – SQB