I’ve got a message with a header which specifies the length of the data. In my example I have a 28 character message to process.
I’m trying to find some way to use a matched number as a repetition count in the same regular expression, something like this non working example:
s = "message 28\r\nthis is some random sentence"
matches = re.match(r"(?P<command>\S+)\s+(?P<bytes>\d+)\r\n(?P<data>.{(?P=bytes)})", s, re.DOTALL).groupdict()
My understanding is my (?P=bytes) is a match for the same string matched by the “bytes” named group rather than allowing me to arbitrarily alter the regular expression and that’s why it’s not working, but is there some way to achieve what I want without passing my string thru two regexs?
It’s not possible to write a single regular expression that can match a length and then use that length as a backreference in a quantifier.
You can use a regular expression to find the length, and then use an ordinary string slicing operation to extract the appropriate characters from the string.