Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
287 views
in Technique[技术] by (71.8m points)

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

I am looking for a proper and robust way to find and replace all newline or breakline chars from a String independent of any OS platform with .

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")
                    .replaceAll("
", "\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
and all newline chars
should be replaced in this example.

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

If you want literal then following should work:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...