Search code examples
javabuffernettyquickfix

How to get a specific string pattern from a continous buffer/byte array in Netty JAVA?


I am currently using Netty. Now the problem is, I want retrieve a specific string from the buffer. For example, if the buffer data is as follows :

8=FIX.4.2|9=00815|35=W|49=TT_PRICE|56=SAP0094X|10=134|8=FIX.4.2|9=00816|35=W49=TT_PRICE|56=SAP0094X|10=121

Now I want the strings starting with "8=xxx" and ending with "10=xxx". You can clearly see that we have two strings appended in the buffer. Note that the above data is in a byte array. So,sometimes I get the exact string and some time I get the string and another half of the full string appended. All I want is , how can I get the exact String starting from "8=xxx" to "10=xxx". I have seen DelimiterBasedFrameDecoder class in Netty that simply checks delimiter specified and gives us the strings. In the same way how can I do this ?


Solution

  • My suggestion would be to translate the buffer and use a regex to match your target substrings:

    ByteBuffer bb = /* byte buffer */
    String text = new String(bb.array(), 0, bb.position(), bb.remaing(), Charset.defaultCharset());
    
    // I assume that this is the string: "8=FIX.4.2|9=00815|35=W|49=TT_PRICE|56=SAP0094X|10=134|8=FIX.4.2|9=00816|35=W49=TT_PRICE|56=SAP0094X|10=121"
    
    // If you need info on the regex just ask for it
    Pattern r = Pattern.compile("(8=\\w\\w\\w)[\\s\\S]*?(10=\\w\\w\\w)");
    Matcher m = r.matcher(text);
    
    while (m.find()) {
         System.out.println(m.group());
    }
    

    Note that Charset.defaultCharset() could be changed base on which encoding your ByteArray is using