我正在尝试编写一个使用 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):
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
<小时/>
演示
关于Python,加拿大地址正则表达式验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29859743/