【问题标题】:Remove all unwanted lines after content in text file in Java删除Java文本文件内容后所有不需要的行
【发布时间】:2015-07-18 18:22:40
【问题描述】:

我已经看到如何使用正则表达式模式在读取文件时删除所有空行,但我想在所有内容之后删除所有不必要的行。例如:

输入

asdiofhpaiodf

(空行,不要删除

asdfihap[sdifh

asdpiofhaspdif

asiodfhpai[sdfh

(空行,删除

(空行,删除


输出

asdiofhpaiodf

(空行)

asdfihap[sdifh

asdpiofhaspdif

asiodfhpai[sdfh

【问题讨论】:

  • 换句话说(更清晰):您想删除所有尾随的空行吗?
  • 定义“不需要的行”。您还可以展示到目前为止您尝试过的内容吗?
  • @laune 是的,这就是我的意思。我不知道我从哪里开始。我不是太古德
  • 我们如何代表line separators in regex?我们如何代表end of string in regex?你也确定你需要正则表达式吗? trim() 似乎很适合这里。
  • 如果您接受\s+$ 作为答案,那么这是一个重复的问题,应该是marked

标签: java regex


【解决方案1】:

你可以用

修剪字符串的结尾
String trimmedContents = origContents.replaceAll("\\s+$", "");

【讨论】:

  • 这取决于 origContents 应该包含什么,它与 OP 在 Q 和 cmets 中写的内容相矛盾。奇怪...
【解决方案2】:

为了补充 stribizhev 的答案,您可能还想使用 System.lineSeparator() 而不是 \s(在大多数情况下 \s 更有用,但我不知道您的需求)

既然我正在发布答案(还不能制作 cmets),我还不如出去。我的印象是您正在尝试重新调整文件的大小。 (我再次使用System.lineSeparator() 来展示如何使用它。

    String regex = "[^"+ System.lineSeparator() + "]" + System.lineSeparator() + "$"; //or use "\\S\\s*$";
    Matcher whiteSpace = Pattern.compile(regex).matcher("");
    int threshold = 4; //number of characters to look back at the end of file.
    byte[] readBytes = new byte[threshold]; //for whatever reason we can't just read in a string :/
    try ( RandomAccessFile file = new RandomAccessFile(input_file, "rw")){
        //start at the end of file, look for non line separator character.
        long cursor;
        for(cursor = file.length() - threshold; cursor > 0 ; cursor=cursor-threshold){
            file.seek(cursor);
            file.readFully(readBytes);
            if(whiteSpace.reset(new String(readBytes)).find()){
                cursor = cursor + whiteSpace.start() + 1;
                break;
            }
        }
        file.setLength(cursor);
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

不知道性能如何,但我没有读入整个文件,而是从头开始。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-09-18
    • 1970-01-01
    • 2018-01-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多