【问题标题】:Java remove unwanted spaces in a text file and replace with characterJava删除文本文件中不需要的空格并替换为字符
【发布时间】:2016-08-22 03:32:47
【问题描述】:

我有以下文本文件。我想删除行和空格,以便文本文件有一个清晰的分隔符来处理。我想不出有什么办法可以消除线条之间的空隙,有什么办法吗?

Student+James Smith+Status: Current Student+Student+James Fits+Status: Not a current Student

文本文件

Student
     James Smith

Status: Current Student

Student
     James Fits

Status: Not a current Student

【问题讨论】:

    标签: java regex writer reader


    【解决方案1】:

    我知道这个

    a.replaceAll("\\s+","");
    

    删除空格。 您可以以类似的方式删除行尾字符

    a.replaceAll("\n","");
    

    其中 'a' 是一个字符串。

    【讨论】:

    • \s 包含\n\s\r\f
    • 啊,很高兴知道。我不得不使用它已经很久了。感谢您提供有用的见解,朋友。
    【解决方案2】:

    使用regex 将整个文本放入一个字符串中

    string txt = "whole String";
    String formatted = txt.replaceAll("[^A-Za-z0-9]", "-");
    

    这将导致更改 + 符号和 " " 以替换为 "-" 符号。所以现在你有了一个特定的分隔符。

    【讨论】:

      【解决方案3】:

      类似 find \s*\r?\n\s* replace +

      修剪空白并添加分隔符“+”
      结果:

      Student+James Smith+Status: Current Student+Student+James Fits+Status: Not a current Student
      

      【讨论】:

        【解决方案4】:

        尝试使用这个。

        \n+\s*
        

        像这样使用它:

        yourStrVar.replaceAll("\n+ *", "+")
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2018-11-04
          • 1970-01-01
          • 2020-03-16
          • 2014-08-26
          • 2017-10-19
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多