有效方式匹配大于最大字符串限制的OutputStream上的正则表达式模式

问题描述 投票:1回答:1

我正在尝试找到一种有效的方法来对大小超过String's max size的ByteArrayOutputStream进行模式匹配。

在适合单个字符串的ByteArrayOutputStream上进行模式匹配很简单:

private boolean doesStreamContainPattern(Pattern pattern, ByteArrayOutputStream baos) throws IOException {

    /*
     *  Append external source String to output stream...
     */

    if (pattern != null) {
        String out = new String(baos.toByteArray(), "UTF-8");
        if (pattern.matcher(out).matches()) {
            return true;
        }
    }

    /*
     *  Some other processing if no pattern match
     */
    return false;
}

但是如果baos的大小超过String的最大大小,问题将变成:

  1. baos输入多个字符串。
  2. “”滑动“模式匹配那些多个String的串联(即原始baos内容)。

[步骤2看起来比步骤1更具挑战性,但我知道Unix sed之类的实用程序仅对文件执行此操作。

完成此任务的正确方法是什么?

java string outputstream
1个回答
1
投票

您可以编写一个简单的包装器类以从流中实现CharSequence

class ByteArrayCharSequence implement CharSequence {
    private byte[] array;
    public StreamCharSequence(byte[] input) {
        array = input;
    }

    public char charAt(int index) {
        return (char) array[index];
    }
    public int length() {
        return array.length;
    }
    public CharSequence subSequence(int start, int end) {
        return new ByteArrayCharSequence(Arrays.copyOfRange(array, start, end));
    }
    public String toString() {
        // maybe test whether we exceeded max String length
    }
}

然后匹配依据

private boolean doesStreamContainPattern(Pattern pattern, ByteArrayOutputStream baos) throws IOException {
    if (pattern != null) {
        CharSequence seq = new ByteArrayCharSequence(baos.toByteArray());
        if (pattern.matcher(seq).matches()) {
            return true;
        }
    }

    /*
     *  Some other processing if no pattern match
     */
    return false;
}

[将边缘强制转换为char并使用copyOfRange时,边缘周围明显很粗糙,但是它在大多数情况下应该可以使用,并且可以针对那些不适合的情况进行调整。

© www.soinside.com 2019 - 2024. All rights reserved.