用Java解析美国地址的邮政编码 问题是如何检测字符串中的5位数字。因此,找到我们的邮政编码。
旁注:我想将代码与GWT一起使用,因此对正则表达式和第三方库有限制。否则,我只会使用。用Java解析美国地址的邮政编码 问题是如何检测字符串中的5位数字。因此,找到我们的邮政编码。,java,string,parsing,postal-code,Java,String,Parsing,Postal Code,旁注:我想将代码与GWT一起使用,因此对正则表达式和第三方库有限制。否则,我只会使用。\\d{5}作为正则表达式,我相信这将是一个起点 代码: 从我的手机上完成,所以请原谅拼写和语法用正则表达式表达非常简单:“^\d{5}” 只需了解如何在java中实现正则表达式映射:和正则表达式 \d{5} 因为邮政编码应该在地址的末尾 \d{5}$ 在美国,邮政编码有两种形式:5位数字(称为邮政编码)和9位数字(称为Zip+4)。以下是解析任何有效美国邮政编码的算法: 假设:起始点是一个包含邮政编码(或
\\d{5}
作为正则表达式,我相信这将是一个起点
代码:
从我的手机上完成,所以请原谅拼写和语法用正则表达式表达非常简单:“^\d{5}”
只需了解如何在java中实现正则表达式映射:和正则表达式
\d{5}
因为邮政编码应该在地址的末尾
\d{5}$
在美国,邮政编码有两种形式:5位数字(称为邮政编码)和9位数字(称为Zip+4)。以下是解析任何有效美国邮政编码的算法: 假设:起始点是一个包含邮政编码(或zip+4)候选项的字符串
如果要使用正则表达式,这应该适用于严格格式的拉链: ^\d{5}([-+]?\d{4})$
- 12345
- 123456789
- 12345-6789
- 12345+6789
- 12345-67ND(是的,你读对了,有时最后两个可以是ND)
(\d{5}(?=\s|$))|(\d{5}-\d{4}(?=\s|$))
下面是我从地址字符串解析zipcode并将其与zipcode数组进行比较的步骤。地址字符串的格式为: 美国州55555市Easy街1234号。它还可以处理55555-5555的拉链
private static final Pattern pattern = Pattern.compile("\\d{5}(?:[-\\s]\\d{4})?");
private static int []zipcodes = {<your array of zips>};
public static boolean isInServiceArea(String address) {
Matcher matcher = pattern.matcher(address);
int zipcode = 0;
if (matcher.find()) {
zipcode = Integer.parseInt(matcher.group(0));
Log.d(TAG, "zipcode: " + zipcode);
}
for (int code : zipcodes) {
if (code == zipcode) {
return true;
}
}
return false;
}
private static final Pattern=Pattern.compile(“\\d{5}(?:[-\\s]\\d{4}”);
私有静态int[]zipcodes={};
公共静态布尔值isInServiceArea(字符串地址){
Matcher Matcher=pattern.Matcher(地址);
int-zipcode=0;
if(matcher.find()){
zipcode=Integer.parseInt(matcher.group(0));
Log.d(标签“zipcode:+zipcode”);
}
for(int代码:zipcodes){
if(代码==zipcode){
返回true;
}
}
返回false;
}
您的意思是在用户键入时识别字符串吗?
private static final Pattern pattern = Pattern.compile("\\d{5}(?:[-\\s]\\d{4})?");
private static int []zipcodes = {<your array of zips>};
public static boolean isInServiceArea(String address) {
Matcher matcher = pattern.matcher(address);
int zipcode = 0;
if (matcher.find()) {
zipcode = Integer.parseInt(matcher.group(0));
Log.d(TAG, "zipcode: " + zipcode);
}
for (int code : zipcodes) {
if (code == zipcode) {
return true;
}
}
return false;
}