第二次更新
最近有个需求是识别身份证或者身份证的详细地址(用的百度识别身份证),划分省市区三级,一开始用的是百度地图的逆地理编码获取的省市区三级,但是突然发现 个人账号只有每次5000次调用的机会 ,超过要额为收费,为了节约成本故此写了一个正则(里面可能不会把所有的地址类型都包含在内),欢迎大家及时反馈,我也会发现后实时更新。
public static Map<String, String> addressResolution(String address) {
//省、市、区
String province = null, city = null, provinceAndCity = null, town = null;
Map<String, String> row = new LinkedHashMap<>();
List<Map<String, String>> table = new ArrayList<>();
Map<String, String> resultMap = new HashMap<>(4);
if (address.startsWith("香港特别行政区")) {
resultMap.put("province", "香港");
return resultMap;
} else if (address.startsWith("澳门特别行政区")) {
resultMap.put("province", "澳门");
return resultMap;
} else if (address.startsWith("台湾")) {
resultMap.put("province", "台湾");
return resultMap;
} else {
String regex="((?<provinceAndCity>[^市]+市|.*?自治州)(?<town>[^县]+县|.*?区|.*?市|.*?旗)(?<detailAddress>.*))";
Matcher m=Pattern.compile(regex).matcher(address);
while(m.find()){
provinceAndCity=m.group(2);
String regex2 = "((?<province>[^省]+省|.+自治区|上海市|北京市|天津市|重庆市|上海|北京|天津|重庆|内蒙古|广西|西藏|宁夏|新疆)(?<city>.*))";
Matcher m2=Pattern.compile(regex2).matcher(provinceAndCity);
while(m2.find()){
province=m2.group(2);
row.put("province", province==null?"":province.trim());
city=m2.group(3);
row.put("city", city==null?"":city.trim());
}
town=m.group(3);
row.put("town", town==null?"":town.trim());
table.add(row);
}
}
if (table != null && table.size() > 0) {
if (StringUtils.isNoneBlank(table.get(0).get("province"))) {
province = table.get(0).get("province");
if (province.contains("自治区")) {
if (province.contains("内蒙古")) {
province = province.substring(0, 4);
} else {
province = province.substring(0, 3);
}
}
}
if (StringUtils.isNoneBlank(province)) {
if (StringUtils.isNoneBlank(table.get(0).get("province"))) {
province = table.get(0).get("province");
if (province.equals("上海市") || province.equals("北京市") || province.equals("重庆市") || province.equals("天津市")||
province.equals("上海") || province.equals("北京") || province.equals("重庆") || province.equals("天津")) {
city = province;
town = table.get(0).get("town");
}else {
town = table.get(0).get("town");
}
}
}
} else {
return resultMap;
}
resultMap.put("province", province);
resultMap.put("city", city);
resultMap.put("district", town);
return resultMap;
}