replace \n and \r\n with
in java

后端 未结 7 1426
余生分开走
余生分开走 2020-11-29 04:49

This has been asked several times for several languages but I can\'t get it to work. I have a string like this

String str = \"This is a string.\\nThis is a l         


        
相关标签:
7条回答
  • 2020-11-29 05:25

    A little more robust version of what you're attempting:

    str = str.replaceAll("(\r\n|\n\r|\r|\n)", "<br />");
    
    0 讨论(0)
  • 2020-11-29 05:25

    It works for me. The Java code works exactly as you wrote it. In the tester, the input string should be:

    This is a string.
    This is a long string.
    

    ...with a real linefeed. You can't use:

    This is a string.\nThis is a long string.
    

    ...because it treats \n as the literal sequence backslash 'n'.

    0 讨论(0)
  • 2020-11-29 05:29

    It works for me.

    public class Program
    {
        public static void main(String[] args) {
            String str = "This is a string.\nThis is a long string.";
            str = str.replaceAll("(\r\n|\n)", "<br />");
            System.out.println(str);
        }
    }
    

    Result:

    This is a string.<br />This is a long string.
    

    Your problem is somewhere else.

    0 讨论(0)
  • 2020-11-29 05:30

    This should work. You need to put in two slashes

    str = str.replaceAll("(\\r\\n|\\n)", "<br />");
    

    In this Reference, there is an example which shows

    private final String REGEX = "\\d"; // a single digit
    

    I have used two slashes in many of my projects and it seems to work fine!

    0 讨论(0)
  • 2020-11-29 05:42

    That should work, but don't kill yourself trying to figure it out. Just use 2 passes.

    str  = str.replaceAll("(\r\n)", "<br />");
    str  = str.replaceAll("(\n)", "<br />");
    

    Disclaimer: this is not very efficient.

    0 讨论(0)
  • 2020-11-29 05:43

    For me, this worked:

    rawText.replaceAll("(\\\\r\\\\n|\\\\n)", "\\\n");
    

    Tip: use regex tester for quick testing without compiling in your environment

    0 讨论(0)
提交回复
热议问题