Replace new line/return with space using regex

前端 未结 7 1743
醉梦人生
醉梦人生 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);
    
    0 讨论(0)
  • 2020-12-24 06:48

    This should take care of space, tab and newline:

    data = data.replaceAll("[ \t\n\r]*", " ");
    
    0 讨论(0)
  • 2020-12-24 06:50

    Try

    L.replaceAll("(\\t|\\r?\\n)+", " ");
    

    Depending on the system a linefeed is either \r\n or just \n.

    0 讨论(0)
  • 2020-12-24 06:50

    Your regex is good altough I would replace it with the empty string

    String resultString = subjectString.replaceAll("[\t\n\r]", "");
    

    You expect a space between "text." and "And" right?

    I get that space when I try the regex by copying your sample

    "This is my text. "
    

    So all is well here. Maybe if you just replace it with the empty string it will work. I don't know why you replace it with \s. And the alternation | is not necessary in a character class.

    0 讨论(0)
  • 2020-12-24 06:59

    I found this.

    String newString = string.replaceAll("\n", " ");
    

    Although, as you have a double line, you will get a double space. I guess you could then do another replace all to replace double spaces with a single one.

    If that doesn't work try doing:

    string.replaceAll(System.getProperty("line.separator"), " ");
    

    If I create lines in "string" by using "\n" I had to use "\n" in the regex. If I used System.getProperty() I had to use that.

    0 讨论(0)
  • 2020-12-24 07:08

    You May use first split and rejoin it using white space. it will work sure.

    String[] Larray = L.split("[\\n]+");
    L = "";
    for(int i = 0; i<Larray.lengh; i++){
       L = L+" "+Larray[i];  
    }
    
    0 讨论(0)
提交回复
热议问题