使用正则表达式解析详细地址

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("江苏省连云港市海州区岗埠农场临河警务区"));
    }

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

yymagicer

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值