Reputation: 28074
I would like to be able to get a postcode from a random string.
Strings I may receive
2 Castlebar Park, London, Greater London W5 1BX, UK
The Ludgrove Club, Alan Drive, Barnet EN5 2PU
The Ludgrove Club, Alan Drive, Barnet EN52PU
The Ludgrove Club, Alan Drive, Barnet E5, UK
These are just examples to demonstrate what they might look like.
What I have so far is:
'The Ludgrove Club, Alan Drive, Barnet EN5 2PU'.match(/^([A-Za-z]{1,2}[0-9A-Za-z]{1,2})[ ]?([0-9]{0,1}[A-Za-z]{2})$/)
//returns null
This works on post codes, but not if they are part of a larger string.
Upvotes: 1
Views: 2131
Reputation: 350147
I would check that the zip code starts from a word break, and that the end of it is delimited by a comma or end-of-string:
/(\b[A-Z]{1,2}\d{1,2}( ?\d?[A-Z]{2})?)(?=,|$)/
// Sample data
[
'2 Castlebar Park, London, Greater London W5 1BX, UK',
'The Ludgrove Club, Alan Drive, Barnet EN5 2PU',
'The Ludgrove Club, Alan Drive, Barnet EN52PU',
'The Ludgrove Club, Alan Drive, Barnet E5, UK'
].forEach(input => { // Iterate over them
var m = input.match(/(\b[A-Z]{1,2}\d{1,2}( ?\d?[A-Z]{2})?)(?=,|$)/);
if (m) console.log(m[0]); // Output match
});
Upvotes: 1
Reputation: 17691
Improving @Paul Armstrong answer a bit, in case of a whole string:
"The Ludgrove Club, Alan Drive, Barnet EN5 2PU".split(",").map(s => s.trim().match(/([A-Za-z]{1,2}\d{1,2})(\s?(\d?\w{2}))?/)).filter(e => e)[0][0]
returns "EN5 2PU"
Upvotes: 3
Reputation: 7156
I believe you're looking to match "EN52PU" as well as "EN5 2PU" as well as just "E5". This should do the trick:
/[A-Za-z]{1,2}\d{1,2}(?:\s?(?:\d?\w{2}))?/
See in action with explanations here: https://regex101.com/r/Nbvu58/2
Upvotes: 1