我想驗證一個字符串是否是有效的代碼;特別是它應該是一對兩個字符。想想一個2個字符的國家代碼。使用re
模塊,我想出了以下情況:使用python驗證兩個字符的代碼
valid = re.compile('([a-zA-Z]){2,2}')
if valid.match(s) and len(s) == 2:
return True
else:
return False
我覺得這是不是在所有優化。我怎樣才能優化這個測試?
我想驗證一個字符串是否是有效的代碼;特別是它應該是一對兩個字符。想想一個2個字符的國家代碼。使用re
模塊,我想出了以下情況:使用python驗證兩個字符的代碼
valid = re.compile('([a-zA-Z]){2,2}')
if valid.match(s) and len(s) == 2:
return True
else:
return False
我覺得這是不是在所有優化。我怎樣才能優化這個測試?
只返回一個簡單的測試結果爲str.isalpha()
加上長度測試:
return len(s) == 2 and s.isalpha()
在默認C
區域字節字符串(例如,你沒有與locale
模塊更改地區)是」只有對於包含兩個ASCII字母(大寫或小寫)的字符串才適用。
如果必須使用正則表達式,然後錨表達:
return re.match('^[a-zA-Z]{2}$', s) is not None
的is not None
測試也給你一個布爾值。 ^
錨定暗示re.match()
,但明確表示不會造成傷害。
不使用正則表達式快但是:
>>> import timeit, re, random
>>> tests = [''.join([chr(random.randrange(256)) for _ in range(2)]) for _ in range(1000)]
>>> def test_str_isalpha(s):
... return len(s) == 2 and s.isalpha()
...
>>> def test_regex(s, pattern=re.compile('^[a-zA-Z]{2}$')):
... return pattern.match(s) is not None
...
>>> timeit.timeit('for s in tests: test(s)', 'from __main__ import tests, test_str_isalpha as test', number=10000)
2.140676975250244
>>> timeit.timeit('for s in tests: test(s)', 'from __main__ import tests, test_regex as test', number=10000)
3.8515820503234863
太棒了!你能否添加一個解釋'return'語法的鏈接? – Dror 2014-09-01 13:15:21
@Dror:什麼部分的表達不清楚?我所做的只是在一個[比較表達式]中使用[布爾表達式](https://docs.python.org/2/reference/expressions.html#boolean-operations)(https://docs.python.org /2/reference/expressions.html#not-in)。 – 2014-09-01 13:48:56
好了,你可以用錨'^'...''$正則表達式,然後你就不需要了'len'檢查。您也可以使用「{2}」而不是「{2,2}」,並且不需要圍繞字符類使用括號。但是字符串格式的確切要求是什麼?兩封信? – 2014-09-01 12:56:46
你的正則表達式應該是'r'^ [a-zA-Z] {2} $'' – 2014-09-01 12:58:00
在正則表達式@AvinashRaj中有一個額外的''''。 – 2014-09-01 13:01:44