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
廣東省|深圳市|南山區


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM