I'm using airlift.joni, a new framework for regex. The main function of this framework is change string to byte[] and then do regex match and similar works. But since all elements are byte[], I can't use replace function in string and have to write my own replacement function.
I can get the start and end of the to-be-replaced pattern in a byte[] but don't know what's the proper way to replace it with a new byte[].
say we have a
byte[] A = new byte[10];
I want to replace A[2] to A[3] with a
byte[] B
whose length may not be 2. Is there some good way to do this? I only have the idea of creating a new array with length A.length+B.length-2 and copy every corresponding byte, but this will make the code too long.
You have to allocate a new array for the result and then use System.arraycopy.
byte[] a = /*Allocated and initialized elsewhere*/;
byte[] b = /*Allocated and initialized elsewhere*/;
int replaceStart = 2; // inclusive
int replaceEnd = 4; // exclusive
byte[] c = new byte[a.length - (replaceEnd - replaceStart) + b.length];
System.arraycopy(a, 0, c, 0, replaceStart);
System.arraycopy(b, 0, c, replaceStart, b.length);
System.arraycopy(a, replaceEnd, c, replaceStart + b.length, a.length - replaceEnd);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With