【问题标题】:regex to extract postal code from an address正则表达式从地址中提取邮政编码
【发布时间】:2021-01-20 06:37:12
【问题描述】:

我有一个地址列表已合并如下所示的邮政编码

65 Windermere Ave., Toronto, ON, M6S 3J4
15 Bruyeres Mews, Toronto, ON M5V 0G8, Canada
M6M1N7, Canada
437 revus Ave, L5G 1S2, Mississauga, ON
, ST. CATHARINES L2M 6Z2 ON
15 Viking Lane, Toronto M9B0A4 ON

我试过这个正则表达式来提取邮政编码,但没有输出

^.{3}(?:[\s]).{3}^$

更新

邮政编码示例:M6S 3J4,L5G 1S2,M9B0A4

【问题讨论】:

  • this 会有帮助吗?

标签: python-3.x regex


【解决方案1】:

你可以试试这个正则表达式(([A-Z]\d[A-Z])+\s?\d[A-Z]\d),它会查找所有大写字母后跟数字和其他大写字母,然后检查是否有空格后跟数字大写字母和另一个数字。

import re

txt = """
65 Windermere Ave., Toronto, ON, M6S 3J4
15 Bruyeres Mews, Toronto, ON M5V 0G8, Canada
M6M1N7, Canada
437 revus Ave, L5G 1S2, Mississauga, ON
, ST. CATHARINES L2M 6Z2 ON
15 Viking Lane, Toronto M9B0A4 ON
"""

print([i[0] for i in re.findall(r"(([A-Z]{1}\d{1}[A-Z]{1})+\s?(\d{1}[A-Z]{1}\d{1})*)", txt)])

输出

['M6S 3J4', 'M5V 0G8', 'M6M1N7', 'L5G 1S2', 'L2M 6Z2', 'M9B0A4']

【讨论】:

  • {1} 是不必要的
  • @anubhava 谢谢我从正则表达式中删除了{1}
【解决方案2】:

Canadian postal codes 采用A1A 1A1 格式,其中A 是一个字母,1 是一个数字。你最好在你的正则表达式中明确匹配。

一个有效的正则表达式如下所示:

[A-Z]\d[A-Z]\s?\d[A-Z]\d

需要注意的几点:

  • 您当前的正则表达式正在锚定在这种情况下您不想做的匹配
  • 您将希望使用re.search 而不是re.match,因为re.match anchors the match
  • 使用?\s 设为可选(这意味着出现0 次或1 次)

这是一个工作示例:

lines = '''65 Windermere Ave., Toronto, ON, M6S 3J4
15 Bruyeres Mews, Toronto, ON M5V 0G8, Canada
M6M1N7, Canada
437 revus Ave, L5G 1S2, Mississauga, ON
, ST. CATHARINES L2M 6Z2 ON
15 Viking Lane, Toronto M9B0A4 ON'''

import re

for s in lines.split('\n'):
    m = re.search(r'([A-Z]\d[A-Z]\s?\d[A-Z]\d)', s)
    if m:
        print(m.group(1))

输出:

M6S 3J4
M5V 0G8
M6M1N7
L5G 1S2
L2M 6Z2
M9B0A4

如果您想要一个完全通用的解决方案来匹配来自世界各地的邮政编码,请查看this post

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-06-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-07
    • 2012-03-13
    • 1970-01-01
    相关资源
    最近更新 更多