11

我正在寻找一种适当且强大的方法来查找和替换独立于任何操作系统平台的所有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;
    }
}

例子:

输入字符串:

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.

但是,它返回了相同的输入字符串。就像它放置 \n 并再次将其解释为换行符。请注意,如果您想知道为什么有人想要\n在那里,这是用户将字符串放在 XML 后缀中的特殊要求。

4

3 回答 3

29

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

String repl = str.replaceAll("(\\r|\\n|\\r\\n)+", "\\\\n")
于 2013-11-11T15:15:11.510 回答
3

这似乎运作良好:

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"));

顺便说一句,您不需要捕获异常。

于 2013-11-11T15:19:59.533 回答
2

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

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\n a 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 \n a String with \n Different Newlines  and other things.
于 2013-11-11T15:22:48.277 回答