删除 java 字符串中选定的新行并保持字符串顺序

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

我想从给定的字符串格式中删除新行

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

输出应该是这样的:

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

我知道我可以使用正则表达式或全部替换为“\n” 但在那种情况下,所有字符串将被替换为一行,我想要的字符串的顺序将不会保持不变。?

一种选择是以全点模式对以下模式进行正则表达式替换:

\r?\n\s*

然后,换一个换行符,保留原来的单个换行符。

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);

这会打印:

Before:
Line 1



 Line 2 blah blah blah


   Line 3 the end.

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

Project structure

input.txt

       This is test;



 This is new test;




 This is new test2;

 This is another string test;








 this is more space string test;

Main.clas

public class Main {
   private static String input = "";
   public static void main(String[] args) throws IOException {
       //Reading the file, taking into account all spaces and margins.
        Files.lines(Paths.get("src/input.txt"), StandardCharsets.UTF_8).forEach(e->{
           input = input.concat(e);
           input = input.concat("\n");
        });

        while (input.contains("\n\n")){
            input = input.replace("\n\n","\n");
        }
        //trim the margins on both sides
        input = input.trim();
        System.out.println(input);
    }
}

结果

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

试试这个。

String text = Files.lines(Paths.get("input.txt"))
    .map(line -> line.trim())
    .filter(line -> !line.isEmpty())
    .collect(Collectors.joining("\n"));
System.out.println(text);

输出

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