使用字符串中的\ n查找并替换所有NewLine或BreakLine字符 - 与平台无关 [英] Find and replace all NewLine or BreakLine characters with \n in a String - Platform independent

查看:118
本文介绍了使用字符串中的\ n查找并替换所有NewLine或BreakLine字符 - 与平台无关的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

示例:

输入字符串:

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并再次将其解释为Newline。
请注意,如果你想知道为什么有人想要 \ n ,那么用户就要特别要求将字符串放在XML后面。

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 \n in there, this is a special requirement by user to place the String in XML afterwords.

推荐答案

如果你想要文字 \ n 那么下面应该有效:

If you want literal \n then following should work:

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

这篇关于使用字符串中的\ n查找并替换所有NewLine或BreakLine字符 - 与平台无关的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆