import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* <p>Description: some description </p>
*
* @author : xiaodong.yang
* @date : 2024/11/18 15:07
*/
public class AddressUtil {
/**
* 从地址串中解析提取出省市区等信息
*
* @param address 地址信息
* @return 解析后的地址Map
*/
private static Map<String, String> addressResolution(String address) {
//1.地址的正则表达式
String regex = "(?<province>[^省]+省|[^自治区]+自治区|北京|上海|天津|重庆|澳门|香港|台湾)?" + "(?<city>[^市]+市|[^自治州]+自治州|[^盟]+盟|[^地区]+地区|市辖区)?" + "(?<county>[^县区旗]+(县|区|旗))?" + "(?<address>.+)";
// 编译正则表达式
//2、创建匹配规则
Matcher m = Pattern.compile(regex).matcher(address);
String province;
String city;
String county;
String detailAddress;
Map<String, String> map = new HashMap<>(16);
while (m.find()) {
//加入省
province = m.group("province");
map.put("province", province == null ? "" : province.trim());
//加入市
city = m.group("city");
map.put("city", city == null ? "" : city.trim());
//加入区
county = m.group("county");
map.put("county", county == null ? "" : county.trim());
//详细地址
detailAddress = m.group("address");
map.put("address", detailAddress == null ? "" : detailAddress.trim());
}
return map;
}
public static String getCounty(String address) {
return addressResolution(address).get("county");
}
public static void main(String[] args) {
System.out.println(addressResolution("江苏省泰州市姜堰区顾高镇309县道"));
System.out.println(addressResolution("内蒙古自治区呼伦贝尔市海拉尔区仁德里街汽车公司综合楼27号"));
System.out.println(addressResolution("江苏省徐州市睢宁县樱花社区"));
System.out.println(addressResolution("江苏省连云港市海州区岗埠农场临河警务区"));
}
}