2015-04-25 17 views
1

我試圖編寫一個使用RegEx驗證加拿大地址的Python腳本。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} [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 
+2

什麼是你必須遵守的規則? – Trevor

+0

至少郵政編碼不能有字母(D,F,I,O,Q,U,W,Z)....地址 – djangel321

+0

中的最後幾個號碼看起來不太合適 - 你需要去找一個加拿大地址驗證資源(鏈接?)。寫完之後,正則表達式應該很簡單。關閉作爲offtopic? – smci

回答

1

加拿大郵政編碼不能包含字母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

+0

非常感謝你......我一直在花費一週的時間試圖找出答案。 – djangel321

2

它一直是這樣......永遠:

/[A-Z][0-9][A-Z] ?[0-9][A-Z][0-9]/ 

如果你想限制的第一個字母來唯一有效的第一個字母,然後這很好,但其餘的太複雜了,以至於不是那麼多。

0
[ABCEGHJKLMNPRSTVXY]\d[A-Z] \d[A-Z]\d 

也許它會工作:d