【问题标题】:Remove selected new line in java string and maintain the String order [closed]删除java字符串中选定的新行并维护字符串顺序[关闭]
【发布时间】:2020-12-03 03:37:07
【问题描述】:

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

     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” 但在这种情况下,所有字符串都将被替换为单行,并且我想要的字符串顺序不会被维护。?

【问题讨论】:

  • 我发布这个问题是为了避免暴力破解,因为我的实际文件为 1 MB,如果有任何具体方法,我需要知道

标签: java string replace removing-whitespace


【解决方案1】:

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

\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.

【讨论】:

  • 谢谢蒂姆,它对我有用 :)
【解决方案2】:

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.class

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;

【讨论】:

    【解决方案3】:

    试试这个。

    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;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-03-17
      相关资源
      最近更新 更多