天天看點

正則截取省市縣

package com.elink.util;

import java.util.*;

import java.util.regex.Matcher;

import java.util.regex.Pattern;

public class AddressUtil {

private static final String PROVINCE = "省";
private static final String CITY = "市";
private static final String REGION_1 = "區";
private static final String REGION_2 = "縣";


public static List<Map<String,String>> addressResolution(String address){
    String regex="((?<province>[^省]+省|.+自治區)|上海|北京|天津|重慶)(?<city>[^市]+市|.+自治州)(?<county>[^縣]+縣|.+區|.+鎮|.+局)?(?<town>[^區]+區|.+鎮)?(?<village>.*)";
    Matcher m= Pattern.compile(regex).matcher(address);
    String province=null,city=null,county=null,town=null,village=null;
    List<Map<String,String>> table=new ArrayList<Map<String,String>>();
    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());
        county=m.group("county");
        row.put("county", county==null?"":county.trim());
        town=m.group("town");
        row.put("town", town==null?"":town.trim());
        village=m.group("village");
        row.put("village", village==null?"":village.trim());
        table.add(row);
    }
    return table;
}


public static void main(String[] args) {
           

// XX省XX市XX區;XX省XX市XX市;XX省XX市XX縣;XX市XX區;XX市XX縣

String[] placeList = new String[]{“浙江省杭州市濱江區”,“上海上海市金山區”,“浙江省台州市玉環縣”,“湖北省潛江市潛江經濟開發區”,“湖北省潛江市江漢石油管理局”,“湖北省天門市馬灣鎮”};

for (String place : placeList) {

System.out.println(addressResolution(place));

}

}

}

繼續閱讀