目录
1.导入依赖
2.编写工具类
3.验证
1.导入依赖
<!--为了使用StringUtils-->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.9</version>
</dependency>
2.编写工具类
城市名等信息不具有有效性,假数据
/**
* 解析身份证地址信息
* 如果是直辖市, 省市一致
* @param address
* @return
*/
private static List<String> directManageCityList = Arrays.asList("北京市", "天津市", "上海市","重庆市");
public static Address addressResolution(String address) {
for (String directCity : directManageCityList) {
if (StringUtils.startsWith(address, directCity)) {
address = directCity + address;
break;
}
}
String regex = "(?<province>[^省]+自治区|.*?省|.*?行政区|.*?市|.*?)(?<city>[^市]+自治州|.*?地区|.*?行政单位|.+盟|市辖区|.*?市|.*?县)(?<district>[^县]+县|.+区|.+市|.+旗|.+海域|.+岛)?(?<town>[^区]+区|.+镇)?(?<detail>.*)";
Matcher m = Pattern.compile(regex).matcher(address);
String province = null, city = null, district = null, town = null, detail = null;
List<Map<String, String>> table = new ArrayList<Map<String, String>>();
Map<String, String> row = null;
Address addressObj = new Address();
while (m.find()) {
row = new LinkedHashMap<String, String>();
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号"));
}