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

问题描述

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

     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;