Java使用正则表达式匹配省市县

目录

1.导入依赖

2.编写工具类

3.验证​


1.导入依赖


        
            org.apache.commons
            commons-lang3
            3.9
        

2.编写工具类

城市名等信息不具有有效性,假数据

 /**
     * 解析身份证地址信息
     * 如果是直辖市, 省市一致
     * @param address
     * @return
     */
    private static List directManageCityList = Arrays.asList("北京市", "天津市", "上海市","重庆市");
    public static Address addressResolution(String address) {

        for (String directCity : directManageCityList) {
            if (StringUtils.startsWith(address, directCity)) {
                address = directCity + address;
                break;
            }
        }

        String regex = "(?[^省]+自治区|.*?省|.*?行政区|.*?市|.*?)(?[^市]+自治州|.*?地区|.*?行政单位|.+盟|市辖区|.*?市|.*?县)(?[^县]+县|.+区|.+市|.+旗|.+海域|.+岛)?(?[^区]+区|.+镇)?(?.*)";
        Matcher m = Pattern.compile(regex).matcher(address);
        String province = null, city = null, district = null, town = null, detail = null;
        List> table = new ArrayList>();
        Map row = null;
        Address addressObj = new Address();
        while (m.find()) {
            row = new LinkedHashMap();
            province = m.group("province");
            addressObj.setProvince( province == null ? "" : province.trim());
            city = m.group("city");
            addressObj.setCity(city == null ? "" : city.trim());
            district = m.group("district");
            addressObj.setDistrict( district == null ? "" : district.trim());
            town = m.group("town");
            addressObj.setTown( town == null ? "" : town.trim());
            detail = m.group("detail");
            addressObj.setDetail( detail == null ? "" : detail.trim());

        }
        return addressObj;
    }

    @Data
    public static class Address {
        private String province;
        private String city;
        private String district;
        private String town;
        private String detail;
    }



    public static void main(String[] args) {
        String idCard = "41010119840202457X";
//        System.out.println(IDCardByConstellation(idCard));
        System.out.println(DateUtils.addressResolution("北京市五一路103号"));
        System.out.println(DateUtils.addressResolution("重庆市渝北区长河路103号"));
        System.out.println(DateUtils.addressResolution("河北省邯郸市继光镇刘家村203号"));
    }

3.验证
Java使用正则表达式匹配省市县_第1张图片

你可能感兴趣的:(java)