2017-10-19 119 views
3

我被要求創建一個程序來識別密碼是否有效。我正在努力的一部分是確定是否有兩個相同的字符彼此相鄰。幫助將不勝感激,這裏是節目至今:確定是否有兩個相鄰字符相同的字符

import re 

pswrd = input("Enter Desired Password:") 

if len(pswrd) < 6: 
    print("Password must have more than 6 characters.") 
if len(pswrd) > 15: 
    print("Password must have no more than 15 characters.") 
if re.search("[$#@]",pswrd): 
    print("Password must have no special characters.") 
if not re.search("[0-9]",pswrd): 
    print("Password must contain a number.") 
if not re.search("[a-z]",pswrd): 
    print("Password must contain a lower case letter.") 
if not re.search("[A-Z]",pswrd): 
    print("Password must contain an upper case letter.") 
+0

測試和最小密碼長度不同意的答覆。 (「少於6」不是「超過6」的相反) – trentcl

回答

2

返回FALSE正則表達式來檢查相鄰字符是

(.)\1 

句點(。)匹配任何字符。括號會在該字符周圍創建一個捕獲組,然後由\ 1引用該組。

因此,條件是:

if re.search(r"(.)\1", pswrd) 

注意正則表達式之前將R字。這使它成爲一個原始字符串。正則表達式應始終爲原始字符串。這可以確保正則表達式中的某些特殊字符(如\ b)在傳遞給re模塊之前不會被解釋。

您可以測試正則表達式的位置:http://regexr.com/3h0g0

1

我想正則表達式r'(.)\1'應該做你要找的內容,其中\1爲向後引用。

0

一種方法是使用anyall功能:

pswrd = input("Enter Desired Password:") 
if any(all(b[0] == b[i] for i in range(len(b))) for b in [[pswrd[c], pswrd[c+1]] for c in range(len(pswrd)-1)]): 
    pass 
+0

你能詳細說明所有這一切嗎?我想在xrange(len(pswrd)-1)中有'all(pswrd [i]!= pswrd [i + 1])'不是更簡單嗎? – ryachza

0

你可以使用反向引用和捕獲組。

(.)\1 

如果有兩個相同的字符彼此相鄰,這將匹配。

對於兩個以上的字符,您可以使用以下內容。

(.)\1+ 

看看它here

0

你可以list()密碼進入列表,並做到這一點:

pswrd = 'assdfds' 
pswrd = list(pswrd) 
for i in range(len(pswrd)): 
    try: 
     if pswrd[i] == pswrd[i+1]: 
      a = True 
      break 
    except IndexError: 
     a = False 
     break 
    else: 
     continue 
    a = False 
print(a) 

返回true,但如果還有點中彼此相鄰的兩個字母是相同

+0

我剛剛意識到這是比其他更基本的__bit__ – AJ123

相關問題