Replace new line/return with space using regex

前端 未结 7 1777
醉梦人生
醉梦人生 2020-12-24 06:36

Pretty basic question for someone who knows.

Instead of getting from

\"This is my text. 

And here is a ne         


        
7条回答
  •  北海茫月
    2020-12-24 06:45

    \s is a shortcut for whitespace characters in regex. It has no meaning in a string. ==> You can't use it in your replacement string. There you need to put exactly the character(s) that you want to insert. If this is a space just use " " as replacement.

    The other thing is: Why do you use 3 backslashes as escape sequence? Two are enough in Java. And you don't need a | (alternation operator) in a character class.

    L.replaceAll("[\\t\\n\\r]+"," ");
    

    Remark

    L is not changed. If you want to have a result you need to do

    String result =     L.replaceAll("[\\t\\n\\r]+"," ");
    

    Test code:

    String in = "This is my text.\n\nAnd here is a new line";
    System.out.println(in);
    
    String out = in.replaceAll("[\\t\\n\\r]+"," ");
    System.out.println(out);
    

提交回复
热议问题