日期:2014-05-19 浏览次数:20799 次
public class Replacement { public static void main(String[] args) { String str = "<cc>\r\n" + " <c code=\"3\">100</c>\r\n" + " <c code=\"5\">100</c>\n" + "</cc>"; System.out.println(str); System.out.println(); str = str.replaceAll("(?<=>)\\s+(?=<)", ""); System.out.println(str); } }
------解决方案--------------------
为了不把标签中元素中纯空格替换掉的话(像下面 /cc/c[@code='5'] 中的空格),可以改成这样:
public class Replacement { public static void main(String[] args) { String str = "<cc>\r\n" + " <c \n" + " \r\n\t" + "\r\n" + "\t code=\"3\"> \n" + " 100\t \r\n" + " \n" + " </c>\r\n" + " <c code=\"5\"> </c>\t\n" + "\n \t\n\t" + "</cc>"; System.out.println(str); System.out.println(); str = str.replaceAll("[\\s&&[^\r\n]]*(?:[\r\n][\\s&&[^\r\n]]*)+", ""); System.out.println(str); } }