Search code examples
javastringreplaceremoving-whitespace

Remove selected new line in java string and maintain the String order


I want to remove the new line from the given string format

     This is test;
 
 
 
 This is new test;
 
 
 
 
 This is new test2;
 
 This is another string test;
 
 
 
 
 
 
 
 
 this is more space string test; 

Output should be like this:

 This is test;
 This is new test;
 This is new test2;
 This is another string test;
 this is more space string test; 

I know I can use regex expression or replace all with "\n" but in that case, all the string will be replaced in single line and the order of string which i want won't be maintained.?


Solution

  • One option would be to do a regex replacement on the following pattern, in dot all mode:

    \r?\n\s*
    

    Then, just replace with a newline, to retain an original single newline.

    String input = "Line 1\r\n\n\n\n     Line 2 blah blah blah\r\n\r\n\n   Line 3 the end.";
    System.out.println("Before:\n" + input + "\n");
    input = input.replaceAll("(?s)\r?\n\\s*", "\n");
    System.out.println("After:\n" + input);
    

    This prints:

    Before:
    Line 1
    
    
    
     Line 2 blah blah blah
    
    
       Line 3 the end.
    
    After:
    Line 1
    Line 2 blah blah blah
    Line 3 the end.