[英]Python, Canadian Address RegEx validation
我試圖編寫一個Python腳本,使用RegEx驗證加拿大地址。
例如,此地址有效:
" 123 4th Street, Toronto, Ontario, M1A 1A1 "
但這個是無效的:
" 56 Winding Way, Thunder Bay, Ontario, D56 4A3"
我已經嘗試了許多不同的組合,保持加拿大郵政編碼的規則,如最后6個字母數字位不能包含字母(D,F,I,O,Q,U,W,Z),但所有條目似乎都是無效的。 我試過“('^ [ABCEGHJKLMNPRSTVXY] {1} \\ d {1} [AZ] {1} * \\ d {1} [AZ] {1} \\ d {1} $')”但仍然無效
這就是我到目前為止所擁有的
import re
postalCode = " 123 4th Street, Toronto, Ontario, M1A 1A1 "
#read First Line
line = postalCode
#Validation Statement
test=re.compile('^\d{1}[ABCEGHJKLMNPRSTVXY]{1}\d{1}[A-Z]{1} *\d{1}[A-Z]{1}\d{1}$')
if test.match(line) is not None:
print 'Match found - valid Canadian address: ', line
else:
print 'Error - no match - invalid Canadian address:', line
就像這樣......永遠:
/[A-Z][0-9][A-Z] ?[0-9][A-Z][0-9]/
如果你想將第一個字母限制為只有有效的第一個字母,那么這很好,但其余部分太復雜,不能與之相提並論。
加拿大郵政編碼不能包含字母D,F,I,O,Q或U,也不能以W或Z開頭:
這對你有用:
import re
postalCode = " 123 4th Street, Toronto, Ontario, M1A 1A1 "
#read First Line
line = postalCode
if re.search("[ABCEGHJKLMNPRSTVXY][0-9][ABCEGHJKLMNPRSTVWXYZ] ?[0-9][ABCEGHJKLMNPRSTVWXYZ][0-9]", line , re.IGNORECASE | re.DOTALL):
print 'Match found - valid Canadian address: ', line
else:
print 'Error - no match - invalid Canadian address:', line
WRONG - 56 Winding Way, Thunder Bay, Ontario, D56 4A3
CORRECT - 123 4th Street, Toronto, Ontario, M1A 1A1
[ABCEGHJKLMNPRSTVXY]\d[A-Z] \d[A-Z]\d
也許它會起作用:D
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.