通过正则表达式获取字符串中的省市区
//[^省]+省|.+自治区|[^澳门]+澳门|北京|重庆|上海|天津|台湾|[^香港]+香港|[^市]+市) 越前面的优先级越高,会取优先级高的第一个匹配到的进行截取
//^自治州]+自治州|[^特别行政区]+特别行政区|[^市]+市|.*?地区|.*?行政单位|.+盟|市辖区|[^县]+县 越前面的优先级越高,会取优先级高的第一个匹配到的进行截取
//[^县]+县|[^市]+市|[^镇]+镇|[^区]+区|[^乡]+乡|.+场|.+旗|.+海域|.+岛 越前面的优先级越高,会取优先级高的第一个匹配到的进行截取
上代码
package com.example.helloworld.controller;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class AddressUtil {
private AddressUtil() {
}
private static Map<String, String> addressResolution(String address) {
String regex = "(?<province>[^省]+省|.+自治区|[^澳门]+澳门|北京|重庆|上海|天津|台湾|[^香港]+香港|[^市]+市)?(?<city>[^自治州]+自治州|[^特别行政区]+特别行政区|[^市]+市|.*?地区|.*?行政单位|.+盟|市辖区|[^县]+县)(?<county>[^县]+县|[^市]+市|[^镇]+镇|[^区]+区|[^乡]+乡|.+场|.+旗|.+海域|.+岛)?(?<address>.*)";
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 Map<String, String> resolveAddress(String address) {
Map<String, String> addressMap = addressResolution(address);
Map<String, String> map = new HashMap<>();
map.put("receiver_area", addressMap.get("province") + " " + addressMap.get("city") + " " + addressMap.get("county"));
map.put("receiver_address", addressMap.get("address"));
return map;
}
public static void main(String[] args) {
System.out.println(resolveAddress("内蒙古自治区呼伦贝尔市海拉尔区仁德里街汽车公司综合楼27号"));
}
}
结果