2013-04-09 48 views
0

我想,如果它a-zA-Z0-9_-否則一個ValueError將在try子句中執行匹配返回由用戶輸入的密碼。這裏是我的代碼似乎並不奏效行,因爲它允許只是像什麼(?,@#$%^ *)Python3使用re.match檢查,如果密碼持有某些字符

return re.match('^[A-Za-z0-9_-]*$',password) 
+1

定義只是anything_ _allows ......究竟是它匹配的,你不認爲它應該? – 2013-04-09 23:15:41

+0

試試這個:'^ [?! A-Za-z0-9 _-] * $' – 2013-04-09 23:17:20

回答

2

隨着克林閉包,你讓一個空字符串作爲一個正確的密碼。您可以使用+特殊字符相匹配的有效字符一個循環:

def validate(password): 
    match = re.match('^[a-z0-9_-]+$', password, re.I) 
    if match is not None: 
     return password 
    else: 
     raise ValueError 
+2

看他的'regex'我認爲'_-'也是允許的。 – 2013-04-09 23:20:19

+1

呵呵,我不知道在正則表達式語法中的'*'被稱爲「Kleene閉包」或[「Kleene明星」](https://en.wikipedia.org/wiki/Kleene_star),或者它來自數學符號。每天學些新東西。同樣,它不是[Kleene X](http://en.wikipedia.org/wiki/Kleenex)。 :-) – 2013-04-09 23:24:33

+0

@AshwiniChaudhary是的,但OP特別指出_it與a-z,A-Z,0-9_匹配,這似乎比沒有給出預期結果的代碼行更具體。 – 2013-04-09 23:27:03

0

下面是使用isalnum非正則表達式的解決方案:

for c in password: 
    if not (c.isalnum() or c in ['_', '-']): 
     raise ValueError('Invalid character in password') 
1

大綱

使用套和SET-減法可能是一個更簡單的解決方案。

代碼

from string import ascii_letters, digits 

PASSWORD_SET = set(ascii_letters + digits + "_-") 

def has_only_password_letters(candidate): 
    return not(set(candidate) - PASSWORD_SET) 

或:

def has_only_password_letters(candidate): 
    return all(c in PASSWORD_SET for c in candidate) 

測試

>>> def test_password(password): 
...  if has_only_password_letters(password): 
...   print "Okay: ", password 
...  else: 
...   print "Nuh-uh: ", password 
... 
>>> test_password("asdasd123123") 
Okay: asdasd123123 
>>> test_password("asdasd123123!!!") 
Nuh-uh: asdasd123123!!! 
相關問題