一、工具源码
package com.rural_vibration.common.utils;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* @description: 地址解析工具 <br>
* @date: 2024/01/29 12:28 <br>
* @author: Dongjie Wang <br>
* @version: 1.0 <br>
*/
public class AddressParseUtil {
/**
* 解析地址为省市区
*
* @param address 地址键入参数
* @return
*/
public static Map<String, String> parse(String address) {
//正则定义
String regex = "(?<province>[^省]+自治区|.*?省|.*?行政区|.*?市)*(?<city>[^市]+自治州|.*?地区|.*?行政单位|.+盟|市辖区|.*?市)(?<area>[^县]+县|.+区|.+市|.+旗|.+海域|.+岛)?(?<detail>.*)";
//正则解析
Matcher m = Pattern.compile(regex).matcher(address);
String province = null, city = null, area = null, detail = null;
Map<String, String> row = null;
while (m.find()) {
row = new LinkedHashMap<String, String>();
province = m.group("province");
row.put("province", province == null ? "" : province.trim());
city = m.group("city");
row.put("city", city == null ? "" : city.trim());
area = m.group("area");
row.put("area", area == null ? "" : area.trim());
detail = m.group("detail");
row.put("detail", detail == null ? "" : detail.trim());
}
return row;
}
/**
* 测试用例
*/
public static void main(String[] args) {
String address = "江苏省无锡市梁溪区金匮街道";
Map<String, String> parse001 = parse(address);
Set<Map.Entry<String, String>> entries = parse001.entrySet();
for (Iterator<Map.Entry<String, String>> iterator = entries.iterator(); iterator.hasNext(); ) {
Map.Entry<String, String> entry = iterator.next();
String key = entry.getKey();
String value = entry.getValue();
System.out.println(key + " : " + value);
}
}
}
二、类Matcher和Pattern用法请参阅官方文档,文档地址如下
Pattern (Java 2 Platform SE 6)https://download.oracle.com/technetwork/java/javase/6/docs/zh/api/java/util/regex/Pattern.html