Python,正则表达式邮政编码搜索 [英] Python, Regular Expression Postcode search

查看:137
本文介绍了Python,正则表达式邮政编码搜索的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用正则表达式在字符串中查找英国邮政编码.

I am trying to use regular expressions to find a UK postcode within a string.

我在 RegexBuddy 中使用了正则表达式,见下文:

I have got the regular expression working inside RegexBuddy, see below:

\b[A-Z]{1,2}[0-9][A-Z0-9]? [0-9][ABD-HJLNP-UW-Z]{2}\b

我有一堆地址,想从中获取邮政编码,示例如下:

I have a bunch of addresses and want to grab the postcode from them, example below:

123 部分路名
镇、市

PA23 6NH

123 Some Road Name
Town, City
County
PA23 6NH

我将如何在 Python 中解决这个问题?我知道 Python 的 re 模块,但我正在努力让它工作.

How would I go about this in Python? I am aware of the re module for Python but I am struggling to get it working.

干杯

伊夫

推荐答案

使用邮政编码 PA23 6NH、PA2 6NH 和 PA2Q 6NH 重复您的地址 3 次作为测试您的模式并使用维基百科中的正则表达式对您的,代码是..

repeating your address 3 times with postcode PA23 6NH, PA2 6NH and PA2Q 6NH as test for you pattern and using the regex from wikipedia against yours, the code is..

import re

s="123 Some Road Name\nTown, City\nCounty\nPA23 6NH\n123 Some Road Name\nTown, City"\
    "County\nPA2 6NH\n123 Some Road Name\nTown, City\nCounty\nPA2Q 6NH"

#custom                                                                                                                                               
print re.findall(r'\b[A-Z]{1,2}[0-9][A-Z0-9]? [0-9][ABD-HJLNP-UW-Z]{2}\b', s)

#regex from #http://en.wikipedia.orgwikiUK_postcodes#Validation                                                                                            
print re.findall(r'[A-Z]{1,2}[0-9R][0-9A-Z]? [0-9][A-Z]{2}', s)

结果是

['PA23 6NH', 'PA2 6NH', 'PA2Q 6NH']
['PA23 6NH', 'PA2 6NH', 'PA2Q 6NH']

两个正则表达式的结果相同.

both the regex's give the same result.

这篇关于Python,正则表达式邮政编码搜索的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆