Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
844 views
in Technique[技术] by (71.8m points)

regex - Python, Regular Expression Postcode search

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

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

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

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

123 Some Road Name
Town, City
County
PA23 6NH

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.

Cheers

Eef

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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
Town, City
County
PA23 6NH
123 Some Road Name
Town, City"
    "County
PA2 6NH
123 Some Road Name
Town, City
County
PA2Q 6NH"

#custom                                                                                                                                               
print re.findall(r'[A-Z]{1,2}[0-9][A-Z0-9]? [0-9][ABD-HJLNP-UW-Z]{2}', 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)

the result is

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

both the regex's give the same result.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...