Backreference in Regular Expression Quantifier

M

Mike Blake-Knox

I'm trying to use regular expressions to match variable length fields
in a record. The fields are laid out with their length in the first
byte and the data following immediately after the length. I was hoping
to do it by matching the length (two hex characters) then using a
backreference to the length in a quantifier. (If the string is
0808313436382e30000e113431 and the regex is
^(?'length'[0-9a-fA-F]{2})([0-9a-fA-F]{\k<length>}) The length capture
is 08 and I was hoping that ([0-9a-fA-F]{\k<length>} would match the
next eight bytes. Unfortunately, there isn't a match.

Would anyone have a suggestion for doing this?

Thanks

Mike Blake-Knox
 
C

Chad Myers

Mike said:
I'm trying to use regular expressions to match variable length fields
in a record. The fields are laid out with their length in the first
byte and the data following immediately after the length. I was hoping
to do it by matching the length (two hex characters) then using a
backreference to the length in a quantifier. (If the string is
0808313436382e30000e113431 and the regex is
^(?'length'[0-9a-fA-F]{2})([0-9a-fA-F]{\k<length>}) The length capture
is 08 and I was hoping that ([0-9a-fA-F]{\k<length>} would match the
next eight bytes. Unfortunately, there isn't a match.

Would anyone have a suggestion for doing this?

Thanks

Mike Blake-Knox

I don't believe you can do this. Backreferences are only used for
matching again, not as general variables.

For example, if you had a file that looked like this:

Subject: Mike Jones

Blah blah blah Mike Jones blah blah blah blah

Sincerely,
Foo

And you wanted to find any occurances of the "Subject" anywhere else in
the letter, you can capture "Mike Jones" and then later backreference it
to find that string anywhere else in the letter.

-c
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top