[英]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,問題就變成了:
baos
多個字符串。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.