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

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值