使用字符串中的\ n查找并替换所有NewLine或BreakLine字符 – 与平台无关

我正在寻找一种适当而强大的方法来从一个独立于任何操作系统平台的String查找和替换所有newlinebreakline newline字符\n

这是我尝试过的,但并没有真正奏效。

 public static String replaceNewLineChar(String str) { try { if (!str.isEmpty()) { return str.replaceAll("\n\r", "\\n") .replaceAll("\n", "\\n") .replaceAll(System.lineSeparator(), "\\n"); } return str; } catch (Exception e) { // Log this exception return str; } } 

例:

输入字符串:

 This is a String and all newline chars should be replaced in this example. 

预期输出字符串:

 This is a String\nand all newline chars\nshould be replaced in this example. 

但是,它返回相同的输入String。 就像它放置\ n并再次将其解释为Newline。 请注意,如果你想知道为什么有人想要\n ,那么用户特别要求将字符串放在XML后面。

如果你想要文字\n那么以下应该工作:

 String repl = str.replaceAll("(\\r|\\n|\\r\\n)+", "\\\\n") 

这似乎运作良好:

 String s = "This is a String\nand all newline chars\nshould be replaced in this example."; System.out.println(s); System.out.println(s.replaceAll("[\\n\\r]+", "\\\\n")); 

顺便说一下,你不需要捕获exception。

哦,当然,你可以用一行正则表达式做到这一点,但有趣的是什么?

 public static String fixToNewline(String orig){ char[] chars = orig.toCharArray(); StringBuilder sb = new StringBuilder(100); for(char c : chars){ switch(c){ case '\r': case '\f': break; case '\n': sb.append("\\n"); break; default: sb.append(c); } } return sb.toString(); } public static void main(String[] args){ String s = "This is \r\na String with \n Different Newlines \f and other things."; System.out.println(s); System.out.println(); System.out.println("Now calling fixToNewline...."); System.out.println(fixToNewline(s)); } 

结果

 This is a String with Different Newlines and other things. Now calling fixToNewline.... This is \na String with \n Different Newlines and other things.