Bor*_*jev 1 java regex removing-whitespace
我正在编写一个我将用于单元测试的函数.我想比较XML文件,但由于其中一个将由第三方库创建,我想减轻由于不同缩进而导致的任何可能的差异.因此我写了以下函数:
private String normalizeXML(String xmlString) {
String res = xmlString.replaceAll("[ \t]+", " ");
// leading whitespaces are inconsistent in the resulting xmls.
res = res.replaceAll("^\\s+", "");
return res.trim();
}
Run Code Online (Sandbox Code Playgroud)
但是,此函数不会删除XML每行的前导间隔.
当我以这种方式编写函数时(第一个正则表达式的差异):
private String normalizeXMLs(String xmlString) {
String res = xmlString.replaceAll("\\s+", " ");
// leading whitespaces are inconsistent in the resulting xmls.
res = res.replaceAll("^\\s+", "");
return res.trim();
}
Run Code Online (Sandbox Code Playgroud)
它确实删除了尾随的空格,但它也使xml显示为单行,当您需要比较差异时,这非常麻烦.
我无法证明为什么第一个实现不会取代前导间隔.有任何想法吗?
编辑:更有趣的是,如果我进行单行操作:
String res = xmlString.replaceAll("^\\s+", "");
Run Code Online (Sandbox Code Playgroud)
此行不会删除任何标识!