2015-04-15 187 views
2

我有一個客戶端要求,當選擇密碼時,用戶不能在密碼字符串中使用多於三個連續的字符或數字。例如:Java - 正則表達式匹配字符串中的連續數字或字符

abc ->> allowed 
abcd ->> not allowed 
wxy ->> allowed 
wxyz ->> not allowed 
stu ->> allowed 
stuv ->> not allowed 

並且具體是ab,bc,kl,op這些是允許的。我的意思是連續的數字或字符允許長度爲三。任何超過三個長度(連續的)都是不允許的。像12345,123456,456789,abcdef,pqrstuv - 這些都是不允許的。

同樣的數字。示例:

123 ->> allowed 
1234 ->> not allowed 
456 ->> allowed 
4567 ->> not allowed 
345 ->> allowed 
3456 ->> not allowed 

和12,45,78,89這些是允許的。

用正則表達式可以實現嗎?如果是這樣,那麼需要一點幫助。

我曾嘗試以下的正則表達式:

^(?:(?!(?:abcd|bcde|cdef|defg|efgh|fghi|ghij|hijk|ijkl|jklm|klmn|lmno|mnop|nopq|opqr|pqrs|qrst|rstu|stuv|tuvw|uvwx|vwxy|wxyz|(a|b|c|d|e|f|g|h|i|j|k|l|m|n|o|p|q|r|s|t|u|v|w|x|y|z)\1{3})).)* 

但這個表達式沒有給出正確的出來放。就像它找到了字符串「abc」和「acm」的匹配。

爲了測試我的正則表達式我使用正則表達式如下測試:

http://www.regexplanet.com/advanced/java/index.html

+7

絕對不會用正則表達式去,作爲你基本上要硬編碼序列,就像你的例子說明。相反,我會解析整個String來獲取字符代碼點增量,並設置一個計數器,當這個增量爲一個連續實例的x個數量時,就會設置一個計數器。 – Mena

+1

http://stackoverflow.com/questions/29509483/how-to-perform-and-operator-in-a-c-sharp-regex – nhahtdh

+0

只是爲了確定,是否允許「abef」? – Pshemo

回答

1

我覺得這樣的事情是最好的代碼完成的,而不是一個正則表達式。我只是使用Character.isLetter(c)並將你的字符轉換爲整數來查看它們是否按順序排列。

+0

在我的情況下,我必須用正則表達式。 – jishan

1

下面是一個快速,骯髒,未優化(可能是越野車),但你想要實現什麼樣的獨立示例。

public static void main(String[] args) { 
    // should not allow 
    System.out.println(hasValidSequence("abcd", 3)); 
    // should not allow 
    System.out.println(hasValidSequence("1234", 3)); 
    // should allow 
    System.out.println(hasValidSequence("abcd", 4)); 
    // should allow 
    System.out.println(hasValidSequence("1234", 4)); 
} 
public static boolean hasValidSequence(String input, int maxAllowed) { 
    // boilerplate validation of empties/nulls 
    if (input == null || input.isEmpty()) { 
     // TODO handle better? 
     return false; 
    } 
    // counter for blowing things up if reached 
    int counter = 0; 
    // char takes int values - initializing as bogus 0 
    char c = (char)0; 
    // iterating input String characters one by one 
    for (int i = 0; i < input.length(); i++) { 
     // previous char is next char as int, - 1 --> they're successive 
     // you can fool around and replace with input.charAt(i) <= i 
     // for indirect sequences or same characters 
     // TODO check it's an alpha numeric! 
     if (c == input.charAt(i) - 1) { 
      // incrementing counter 
      counter++; 
     } 
     // assigning current char 
     c = input.charAt(i); 
     // counter reached? we blow things up! 
     if (counter == maxAllowed) { 
      return false; 
     } 
    } 
    // no counter reached, return true 
    return true; 
} 

輸出

false 
false 
true 
true