简体   繁体   English

从地址字符串中提取邮政编码-JavaScript-英国

[英]Extract post code from an address string - JavaScript - UK

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. 这适用于邮政编码,但不适用于较大的字符串。

I believe you're looking to match "EN52PU" as well as "EN5 2PU" as well as just "E5". 我相信您希望匹配“ EN52PU”,“ EN5 2PU”以及“ 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 在此处查看带有说明的实际操作: https//regex101.com/r/Nbvu58/2

Improving @Paul Armstrong answer a bit, in case of a whole string: 在整个字符串的情况下,改进@Paul Armstrong的答案:

"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" 返回“ EN5 2PU”

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[AZ]{1,2}\\d{1,2}( ?\\d?[AZ]{2})?)(?=,|$)/); if (m) console.log(m[0]); // Output match }); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM