From: Matt Brooks Date: 2009-09-03T01:09:54+09:00 Subject: Re: confusing string parsing problem unknown wrote: > On Wed, Sep 2, 2009 at 10:01 AM, Matt Brooks > wrote: >> 2 byte UINT16 >> >> I want to display each value from the fields, while also removing it >> from the string as I read it out... >> >> My attempt is horrible I know, and I don't think it really runs. > > Can you post an example of your data and code with the incorrect > output and expected output? > >> cat z.rb > string = "" > string << 0.chr << 1.chr > string << 0.chr << 2.chr > string << 2.chr > string << "foo" << "BFO" > string << "bar" << "BFO" > string << 0.chr << 3.chr > > p string > > p string[0..1], string[0..1].unpack('n') > p string[2..3], string[2..3].unpack('n') > p string[0..3].unpack('n2') > > p string[4..4], string[4..4].unpack('C') > p string[0..4].unpack('n2C') > > p string[5..-2].split(/BFO/) > >> ruby -v z.rb > ruby 1.8.7 (2008-08-11 patchlevel 72) [i486-linux] > "\000\001\000\002\002fooBFObarBFO\000\003" > "\000\001" > [1] > "\000\002" > [2] > [1, 2] > "\002" > [2] > [1, 2, 2] > ["foo", "bar", "\000"] Thanks a lot for your reply, i will look into it and see if i can implement using unpack. in the meantime this is a sample output... My current output is: 1st 2 byte field = 3 2nd 2 byte field = 0 Num Pairs = 1 sub_elements = "BFO\0000\000\000\000\001\000\000\0005\000\003\000\000\000\00 0\000\000\000\000\000\001\002\000\000\312+\335V\353\262\000\001\001Internal...and so on for hundreds of bytes more... I, [2009-09-02 11:56:10 #4864] INFO -- : Pairs to get: 1 I, [2009-09-02 11:56:10 #4864] INFO -- : Param Value Name: BFO what i want output to be: I, [2009-09-02 11:56:10 #4864] INFO -- : Pairs to get: 1 I, [2009-09-02 11:56:10 #4864] INFO -- : Param Value Name: BFO I, [2009-09-02 11:56:10 #4864] INFO -- : String Value: whatever the string is till it is null terminated I, [2009-09-02 11:56:10 #4864] INFO -- : Last 2 byte field: 0 And At this point I need the sub_elements string to not contain any of the above parameters printed out, ie. whatever I display is done with and needs to be deleted out of the front of the string. my code: I was redoing my code, and only up to this point. #prints first 5 bytes formated nicely writelog("#{bin_msg.inspect_detailed})") #How many pairs to expect writelog("Pairs to get: #{bin_msg.num_optional_mod_params}") #Remove BFO while printing it as well writelog("Param Value Name: #{bin_msg.sub_elements.slice!(/^BFO/)}") #THIS DOESN'T WORK!!! Needs to scan for possible minus sign, plus up to #variable length number of digits, up to the null termination of the string bin_msg.sub_elements.scan(/-?[0-9]+\Z/) #Needs to then print the next 2 bytes while taking that out of the string as well -- Posted via http://www.ruby-forum.com/.