java正则匹配多个子字符串样例

文本内容:

上海市黄浦区
瑞典
江苏省无锡市
广东省深圳市南山区

我希望分别将字符串中的省份,城市名,城区名匹配出来,如匹配不出来就默认放在省份中。

 1 public static HashMap<String, String> splitCountry(String country) {
 2         HashMap<String, String> ret = new HashMap<String, String>();
 3         Pattern mpattern = Pattern.compile("(((.*省)|(.*市)|(.*区)).*?|.*)");
 4         Matcher mmatcher = mpattern.matcher(country);
 5         String str = "";
 6         while (mmatcher.find()) {
 7             str = mmatcher.group();
 8             if (str.length() > 0) {
 9                 if (str.endsWith("省"))
10                     ret.put("province", str);
11                 else if (str.endsWith("市"))
12                     ret.put("city", str);
13                 else if (str.endsWith("区"))
14                     ret.put("region", str);
15                 else
16                     ret.put("province", str);
17             }
18         }
19         return ret;
20     }
 1 public class TestIP {
 2 
 3     @Test
 4     public void test() {
 5          List<String> cList = new ArrayList<String>();
 6          cList.add("上海市黄浦区");
 7          cList.add("瑞典");
 8          cList.add("江苏省无锡市");
 9                  cList.add("广东省深圳市南山区");
10          for(String country:cList)
11          {
12              HashMap<String,String> dd = IPUtil.splitCountry(country);
13              System.out.println(dd.get("province") + "|" + dd.get("city") + "|" + dd.get("region"));
14          }
15     }
16 
17 }


 程序执行输出结果:

 |上海市|黄浦区
瑞典|null|null
江苏省|无锡市|null
广东省|深圳市|南山区

原文地址:https://www.cnblogs.com/anny-1980/p/3668504.html