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

Ind*_*igo 10 java regex string

我正在寻找一种适当而强大的方法来从独立于任何OS平台中查找和替换所有newlinebreakline字符.String\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;
    }
}
Run Code Online (Sandbox Code Playgroud)

例:

输入字符串:

This is a String
and all newline chars 
should be replaced in this example.
Run Code Online (Sandbox Code Playgroud)

预期输出字符串:

This is a String\nand all newline chars\nshould be replaced in this example.
Run Code Online (Sandbox Code Playgroud)

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

anu*_*ava 28

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

String repl = str.replaceAll("(\\r|\\n|\\r\\n)+", "\\\\n")
Run Code Online (Sandbox Code Playgroud)