至少在我的系統上,做檢查,而無需使用re
快一點。而且,隨着密碼長度的增加,速度差異似乎變得更加明顯。
import re
import timeit
passwords_varied = ("kk", "999999999999999999999999", "kkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkk", "gkrDsh!2", "gjtlssssssssssssssssfsdg43ggw3fa2adada2fagaa2adajjjjjjjjjjjjjjjkhjkhjkhjkd45!", "kit43MM?", "fkthrej!", "483kkED!")
passwords_8chars = ("hktj33cD", "!?gk329s", "fkrK44?a", "dlekAS2$", "??ffD913")
def check1(s):
return len(s) == 8 and \
any(x.isdigit() for x in s) and \
any(x in ("$","!","?") for x in s) and \
any(x.isupper() for x in s)
def check2(s):
if len(s) == 8 and \
re.search(r"\d", s) and \
re.search(r"[$!?]", s) and \
re.search(r"[A-Z]", s):
return True
return False
def run1(passwords):
for password in passwords:
check1(password)
def run2(passwords):
for password in passwords:
check2(password)
def main():
print ("---- list comprehension approach ----")
print ("varying length passwords")
print(timeit.timeit("run1(passwords_varied)", setup="from __main__ import run1, passwords_varied", number=100000))
print ("correct length passwords")
print(timeit.timeit("run1(passwords_8chars)", setup="from __main__ import run1, passwords_8chars", number=100000))
print ""
print "---- 're' approach ----"
print ("varying length passwords")
print(timeit.timeit("run2(passwords_varied)", setup="from __main__ import run2, passwords_varied", number=100000))
print "correct length passwords"
print(timeit.timeit("run2(passwords_8chars)", setup="from __main__ import run2, passwords_8chars", number=100000))
if __name__ == '__main__':
main()
"""
---- list comprehension approach ----
varying length passwords
2.69666814804
correct length passwords
3.31486010551
---- 're' approach ----
varying length passwords
3.27806806564
correct length passwords
4.286420106
"""
來源
2016-06-13 17:49:12
jDo
您是否對任何字符串進行過測試?請添加到問題。正則表達式與您所描述的不匹配。 –
一個簡單的方式來說,順序並不重要,是單獨測試模式 –
我不認爲試圖解決它在一個正則表達式是一個好主意。爲了提高可讀性和可測試性,請使用多重檢查來解決問題,例如像完成[這裏](http://stackoverflow.com/a/32542964/771848)。 – alecxe