Java 在字符串中使用 \n 查找和替换所有 NewLine 或 BreakLine 字符 - 平台无关

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19909579/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 21:14:20  来源:igfitidea点击:

Find and replace all NewLine or BreakLine characters with \n in a String - Platform independent

javaregexstring

提问by Indigo

I am looking for a proper and robust way to find and replace all newlineor breaklinechars from a Stringindependent of any OS platform with \n.

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

This is what I tried, but didn't really work well.

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

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;
    }
}

Example:

例子:

Input String:

输入字符串:

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

Expected Output String:

预期输出字符串:

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

However, it returned the same input String back. Like it placed \n and interpreted it as Newline again. Please note, if you wonder why would someone want \nin there, this is a special requirement by user to place the String in XML afterwords.

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

采纳答案by anubhava

If you want literal \nthen following should work:

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

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

回答by Alper

This seems to work well:

这似乎运作良好:

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

By the way, you don't need to catch exception.

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

回答by MadConan

Oh sure, you could do it with one line of regex, but what fun is that?

哦,当然,你可以用一行正则表达式来完成,但那有什么乐趣呢?

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

}

The result

结果

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.