Use token as variable in pyparsing

I recently started using python / pyparsing to process a string of hex values, and I am having problems with this: Consider this line:

string = "10020304059917368584304025326"

I want the end result to be as follows:

['10', '02', '03', ['04', '05', '9917365843'], ['04', '02', '5326']]

Suppose 04 is a tag that means data (the same concept as in ASN.1), and 05 is the size of this data. I do not see how to use the size variable in pyparsing code. The best I can do is:

byte = Word(hexnums, exact=2)
process = byte + byte + byte + Word(hexnums)
newstring = process.parseString(string)
print (newstring.dump())

Any help would be greatly appreciated.


PS . After using Hooked, my last code is:

from pyparsing import *

string = "10 02 03 04 05 99 17 36 58 43 04 02 53 26"

tag = Word(hexnums, exact=2)
size =  Word(hexnums)
array = Group(tag + countedArray(size))

process = tag + tag + tag + ZeroOrMore(array)

newstring = process.parseString(string)
print (newstring.dump())

What prints:

['10', '02', '03', ['04', ['99', '17', '36', '58', '43']], ['04', ['53', '26']]]

Hope this helps in the future.

+5
source share
2 answers

, BNF ?. , , . , pyparsing - , - , :

Pyparsing countedArray, , . expr , "n" expr

. : PyParsing lookaheads , .

+2

? pyparsing, , "04".

def func( s ):
    d = []
    # while s isn't empty
    while len(s) != 0:
        b = s[0:2]
        if b != '04':
            # if b isn't '04' append it to d
            d.append( b )   
            # shorten s
            s = s[2:]
        else:
            # take the length, as a string
            l = s[2:4]
            # take the length, as an integer
            n = int(s[2:4])
            # record b='04', the length, and then the next values
            d.append( [ b, l, s[4:4+n*2] ] )
            # shorten s
            s = s[4+n*2:]
    return d
0

All Articles