在字符串中查找所有换行符或隔行符并将其替换为 - 独立于平台



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

这是我尝试过的,但效果不佳。

public static String replaceNewLineChar(String str) {
    try {
        if (!str.isEmpty()) {
            return str.replaceAll("nr", "\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 Stringnand all newline charsnshould be replaced in this example.

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

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

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

这似乎效果很好:

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

顺便说一下,你不需要捕捉异常。

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

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 rn 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.

最新更新