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

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

在适合单个String的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. “滑动”匹配多个字符串(即原始baos内容)的模式匹配的模式。

步骤2看起来比步骤1更具挑战性,但是我知道诸如Unix sed之类的实用程序只能在文件上执行此操作。

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

sunicon 回答:有效方式匹配大于最大String限制的OutputStream上的正则表达式模式

您可以编写一个简单的包装器类以从流中实现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并使用边缘边缘public class TestJTextArea { public static void main(final String[] args) { final JPanel panel = new JPanel(new BorderLayout()); panel.setPreferredSize(new Dimension(500,500)); panel.add(new JTextArea(),BorderLayout.CENTER); final JFrame frame = new JFrame("Test"); frame.getContentPane().add(panel,BorderLayout.CENTER); frame.pack(); frame.setResizable(false); frame.setLocationRelativeTo(null); frame.setVisible(true); } } 时,边缘周围明显很粗糙,但是它在大多数情况下都可以使用,您可以针对不适用的情况进行调整。

本文链接:https://www.f2er.com/3168334.html

大家都在问