• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
人生之路,职业之路
读书使人充实,交谈使人机敏,写记使人精确;
“动因+兴趣”——决心-持之以恒-见效
博客园    首页    新随笔    联系   管理    订阅  订阅
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
广东省|深圳市|南山区

posted on 2014-04-16 14:01  FreeBird  阅读(20365)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3