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

时间:2017-01-06 20:31:55

标签: javascript regex

我希望能够从随机字符串中获取邮政编码。

我可能收到的字符串

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

这些只是展示它们的样子的例子。

到目前为止我所拥有的是:

'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

这适用于邮政编码,但如果它们是较大字符串的一部分则不适用。

3 个答案:

答案 0 :(得分:1)

我相信你想要匹配“EN52PU”和“EN5 2PU”以及“E5”。这应该可以解决问题:

/[A-Za-z]{1,2}\d{1,2}(?:\s?(?:\d?\w{2}))?/

请参阅此处的解释:https://regex101.com/r/Nbvu58/2

答案 1 :(得分:1)

改善@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]

返回“EN5 2PU”

答案 2 :(得分:0)

我会检查邮政编码是从单词分词开始的,并且它的结尾是用逗号或字符串结尾分隔的:

/(\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
});