无法删除Java字符串中的换行符(\ n)。甚至有可能吗?

问题描述 投票:3回答:5

基本上,我要做的就是从Java中的字符串中删除换行符。我看过几十个帖子,问类似的问题,他们都说相同的话,但似乎没有一个适合我。这是我有3行的所有代码:

    String text = "\\n          texttexttext     \\n";
    text = text.replaceAll("\\n", "");
    System.out.println(text);

该字符串类似于我实际尝试使用的字符串,但是即使有了这个字符串,我也找不到换行符并将其替换。 replaceAll只是看不到,我也不知道为什么。

我也尝试了很多其他事情,例如

    text = text.replaceAll("\\n", "").replaceAll("\\r", "");

    text = text.replaceAll("\\r\\n|\\r|\\n", " ");

但是什么都找不到。我什至无法使用Regex Pattern和Matcher对象找到它。我正在做的唯一有点不寻常的事情是在Junit Test bean中进行,但是我不敢相信会做任何事情。

java string newline
5个回答
7
投票

原始text中没有换行符。您已经转义了反斜杠,而不是n,因此在\字符串中有实际的反斜杠ntext字符。

您确实必须在正则表达式中转义反斜杠字符,但在文字字符串文本中未转义。

如果将text初始化为"\n texttexttext \n",则它将按预期找到并替换那些换行符。


3
投票
String newLine = System.getProperty("line.separator")
System.out.println(newLine.contains("\n")); // this is a new line
System.out.println(newLine.contains("\\n"));

输出:

true
false

1
投票

如林恩·林恩评论

您的示例文本实际上没有谈论换行符-\\n是字符串\n

另一个谬误是replaceAll希望将正则表达式作为第一个输入。因此,\\n实际上被替换为\n,因为\是转义字符,然后将其解释为换行符-两次转义的情况,因此在您输入的文本中\\不匹配。

如果您尝试

text = text.replaceAll("\\\\n", "");

至少您可以获得预期的结果,因为它既是Java字符串,也是正则表达式,都将\解释为转义字符。


0
投票

除了@rgettman的答案以及为了使其对社区有用之外,下面是一个很棒的Java程序(有关更多信息,您可以从here中阅读整篇文章。)它代替了换行符。

public class StringReplaceTask{


    public static void main(String args[]) {

        // Removing new line characters form Java String
        String sample="We are going to replace newline character \\n "
                + "New line should start now if \\n \n is working";

        System.out.println("Original String: " + sample);

        //replacing \n or newline character so that all text come in one line
        System.out.println("Escaped String: " + sample.replaceAll("\n", ""));


        // removing line breaks from String read from text file in Java
        String text = readFileAsString("words.txt");
        text = text.replace(System.getProperty("line.separator"), "");

    }  

0
投票

如果head ='Hello',但当您打印(head)->'Hello \ n'您可以通过rstrip()或remove()]删除\ n

您可以使用我的代码

head = a [0:(len(head)-1)] >>

删除隐藏在字符串中的\ n。

(对py 3进行测试)祝你好运!

© www.soinside.com 2019 - 2024. All rights reserved.