我試圖使用Python regular expression
來驗證變量的值。Python:使用正則表達式進行數據驗證
驗證規則如下:
- 值可以包含任何的
a-z
,A-Z
,0-9
和*
(無blank
,沒有-
,沒有,
) - 的同一個數字值可以
start
(0-9)
或字母(a-z, A-Z)
或*
- 值可以
end
以數字(0-9)
或字母(a-z, A-Z)
或*
- 在中間,該值可以包含目前我使用下面的代碼片段一些
(0-9)
或字母(a-z, A-Z)
或*
- 任何其他值絕不允許
做驗證:
import re
data = "asdsaq2323-asds"
if re.compile("[a-zA-Z0-9*]+").match(data).group() == data:
print "match"
else:
print "no match"
我覺得應該有一個更好的方法來做到上述。我在尋找的東西像下面這樣:
validate_func(pattern, data)
/* returns data if the data passes the validation rules */
/* return None if the data does not passes the validation rules */
/* should not return part of the data which matches the validation rules */
會有這樣一個內建功能存在嗎?
''\ w \ d \ *] +'不夠嗎?最好的測試方法是做一個質量循環來測試你已有的所有值(在列表/文件中)。當循環中的匹配失敗時,您應該將其打印出來,並對其進行更多研究,瞭解哪些內容出錯,並瞭解如何優化RegEx。 – 2013-03-22 22:38:59