正则表达式
正则表达式测试 正则表达式入门 匹配省、自治区以及四个直辖市作为省
((?<province>[^省]+省|.+自治区)|上海市|北京市|天津市|重庆市)
匹配市、自治州、区作为市
(?<city>[^市]+市|.+自治州|.+区)?
匹配县、市、区、镇、局作为县
(?<country>[^县]+县|.+市|.+区|.+镇|.+局)?
匹配区、镇作为镇
(?<town>[^区]+区|.+镇)?
匹配省市县镇以外其余数据
(?<village>.*)
正则表达式匹配地址获得省市县
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class regex_address {
public static List<Map<String,String>> regexAddress(String address){
String regex = "((?<province>[^省]+省|.+自治区)|上海市|北京市|天津市|重庆市)(?<city>[^市]+市|.+自治州|.+区)?(?<country>[^县]+县|.+市|.+区|.+镇|.+局)?(?<town>[^区]+区|.+镇)?(?<village>.*)";
Matcher matcher = Pattern.compile(regex).matcher(address);
String province = null,city = null,country = null;
ArrayList<Map<String, String>> table = new ArrayList<>();
Map<String,String> row = null;
while (matcher.find()){
row = new LinkedHashMap<String,String>();
String regex2 = "(上海市|北京市|天津市|重庆市)";
Matcher matcher1 = Pattern.compile(regex2).matcher(address);
if (matcher1.find())
province = matcher1.group(1);
else
province = matcher.group("province");
row.put("province",province == null ? "":province.trim());
city = matcher.group("city");
row.put("city",city == null ? "" : city.trim());
country = matcher.group("country");
row.put("country",country == null ? "" : country);
table.add(row);
}
return table;
}
public static void main(String[] args) {
String[] addressList = {"浙江省杭州市西湖区", "江苏省苏州市吴中区", "河南省郑州市新郑市","上海市浦东新区","河南省郑州市新郑市","北京市朝阳区"};
for(String address : addressList){
System.out.println(address);
List<Map<String, String>> address1 = regexAddress(address);
String province = address1.get(0).get("province");
String city = address1.get(0).get("city");
String country = address1.get(0).get("country");
System.out.printf("province:%s,city:%s,country:%s\n",province,city,country);
}
}
}
输出结果
浙江省杭州市西湖区
province:浙江省,city:杭州市,country:西湖区
江苏省苏州市吴中区
province:江苏省,city:苏州市,country:吴中区
河南省郑州市新郑市
province:河南省,city:郑州市,country:新郑市
上海市浦东新区
province:上海市,city:浦东新区,country:
河南省郑州市新郑市
province:河南省,city:郑州市,country:新郑市
北京市朝阳区
province:北京市,city:朝阳区,country:
Process finished with exit code 0
|