簡體   English   中英

有效方式匹配大於最大字符串限制的輸出流上的正則表達式模式

[英]Efficient way match a regex Pattern on an OutputStream greater than max String limit

我試圖找到一種有效的方法來對大小超過String 的 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 max size,問題就變成了:

  1. baos多個字符串。
  2. 在這些多個字符串的串聯上“滑動”模式匹配(即原始baos內容)。

第 2 步看起來比第 1 步更具挑戰性,但我知道像 Unix sed這樣的實用程序可以在文件上執行此操作。

實現這一目標的正確方法是什么?

您可以編寫一個簡單的包裝器 class 來實現 stream 的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的邊緣顯然很粗糙,但它應該適用於大多數情況,您可以針對不適用的情況進行調整。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM