我试图编写一个使用RegEx验证加拿大地址的Python脚本。
例如,此地址有效:
" 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} [A-Z] {1} * \ d {1} [A-Z] {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
最佳答案
加拿大邮政编码不能包含字母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
演示版
http://ideone.com/QAsrUT