简体   繁体   English

使用java将英国邮政编码拆分为两个主要部分

[英]Split UK postcode into two main parts using java

This regular expression for validating postcodes works perfect 这个用于验证邮政编码的正则表达式非常完美

^([Gg][Ii][Rr] 0[Aa]{2})|((([A-Za-z][0-9]{1,2})|(([A-Za-z][A-Ha-hJ-Yj-y][0-9]{1,2})|(([A-Za-z][0-9][A-Za-z])|([A-Za-z][A-Ha-hJ-Yj-y][0-9]?[A-Za-z])))) {0,1}[0-9][A-Za-z]{2})$

but I want to split the postcodes to retrieve the individual parts of the postcode using java. 但我想拆分邮政编码,以便使用java检索邮政编码的各个部分。

How can this be done in java? 怎么能在java中完成?

Here are the official regexes for matching UK postcodes: 以下是匹配英国邮政编码的官方正则表达式:

http://interim.cabinetoffice.gov.uk/media/291370/bs7666-v2-0-xsd-PostCodeType.htm http://interim.cabinetoffice.gov.uk/media/291370/bs7666-v2-0-xsd-PostCodeType.htm

If you want to split a found postcode into it's two parts, isn't it simply a question of splitting on whitespace? 如果你想将找到的邮政编码拆分成两部分,那不就是在空格上拆分的问题吗? A UK postcode's two parts are just separated by a space, right? 英国邮政编码的两个部分只是用空格隔开,对吗? In java this would be: 在java中,这将是:

String[] fields = postcode.split("\\s");

where postcode is a validated postcode and fields[] will be an array of length 2 containing the first and second parts. 其中邮政编码是经过验证的邮政编码,而fields []将是包含第一和第二部分的长度为2的数组。

Edit: If this is to validate user input, and you want to validate the first part, your regex would be: 编辑:如果这是为了验证用户输入,并且您想验证第一部分,那么您的正则表达式将是:

Pattern firstPart = Pattern.compile("[A-Z]{1,2}[0-9R][0-9A-Z]?");

To validate the second part it is: 要验证第二部分,它是:

Pattern secondPart = Pattern.compile("[0-9][A-Z-[CIKMOV]]{2}");

I realise that it's rather a long time since this question was asked, but I had the same requirement and thought that I'd post my solution in case it helps someone out there : 我意识到,问这个问题已经有很长一段时间了,但我有同样的要求,并且认为我会发布我的解决方案,以防有人在那里帮忙:

const string matchString = @"^(?<Primary>([A-Z]{1,2}[0-9]{1,2}[A-Z]?))(?<Secondary>([0-9]{1}[A-Z]{2}))$";

var regEx = new Regex(matchString);
var match = regEx.Match(Postcode);

var postcodePrimary = match.Groups["Primary"];
var postcodeSecondary = match.Groups["Secondary"];

This doesn't validate the postcode, but it does split it into 2 parts if no space has been entered between them. 这不会验证邮政编码,但如果它们之间没有输入空格,它会将其分成两部分。

You can use the Google's recentlly open sourced library for this. 您可以使用Google最近开源的库。 http://code.google.com/p/libphonenumber/ http://code.google.com/p/libphonenumber/

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

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