public List<String> spiltString(String srcString, String c) { List<String> destString = new ArrayList<String>(); if (srcString == null || c == null) { return null; } else { // 特殊字符需转义 if ("\\".equals(c)) { c = "\\\\"; } else { String rex = "[*+?|.$^]"; Pattern pattern = Pattern.compile(rex); Matcher mat = pattern.matcher(c); if (mat.matches()) { // 特殊字符需转义 c = "\\" + c; } } String[] temp = srcString.split(c); for (String str : temp) { if (!str.equals("")) { destString.add(str); } } return destString; } }
要注意的是,"\"转义时要写成"\\\\",“+”转义时要写成“\\+","*"转义时要写成”\\*",以上只是用一个字符进行分割,多个字符的拆分方法类似
【1】单个符号作为分隔符 String address="上海|上海市|闵行区|吴中路"; String[] splitAddress=address.split("\\|"); //如果以竖线为分隔符,则split的时候需要加上两个斜杠【\\】进行转义 System.out.println(splitAddress[0]+splitAddress[1]+splitAddress[2]+splitAddress[3]); String address="上海*上海市*闵行区*吴中路"; String[] splitAddress=address.split("\\*"); System.out.println(splitAddress[0]+splitAddress[1]+splitAddress[2]+splitAddress[3]); String address="上海:上海市:闵行区:吴中路"; String[] splitAddress=address.split("\\:"); System.out.println(splitAddress[0]+splitAddress[1]+splitAddress[2]+splitAddress[3]); String address="上海.上海市.闵行区.吴中路"; String[] splitAddress=address.split("\\."); System.out.println(splitAddress[0]+splitAddress[1]+splitAddress[2]+splitAddress[3]); String address="上海^上海市^闵行区^吴中路"; String[] splitAddress=address.split("\\^"); System.out.println(splitAddress[0]+splitAddress[1]+splitAddress[2]+splitAddress[3]); String address="上海@上海市@闵行区@吴中路"; String[] splitAddress=address.split("@"); System.out.println(splitAddress[0]+splitAddress[1]+splitAddress[2]+splitAddress[3]); String address="上海,上海市,闵行区,吴中路"; String[] splitAddress=address.split(","); System.out.println(splitAddress[0]+splitAddress[1]+splitAddress[2]+splitAddress[3]); 【2】多个符号作为分隔符 String address="上海^上海市@闵行区#吴中路"; String[] splitAddress=address.split("\\^|@|#"); System.out.println(splitAddress[0]+splitAddress[1]+splitAddress[2]+splitAddress[3]);
输出格式:上海上海市闵行区吴中路
原文:http://www.cnblogs.com/leskang/p/6491907.html