sateayam
sateayam

Reputation: 1089

parse HEX value from a string

I am trying to get a hex value from a string with this condition "VALUE: num,num,num,HEX,num,num"

I have the following

% set STRINGTOPARSE "VALUE: 12,12,13,2,9,5271256369606C00,0,0" 
% regexp {(,[0-9A-Z]+,)+} $STRINGTOPARSE result1 result2 result3
1
% puts $result1
,12,
% puts $result2
,12,
% puts $result3

I believe the condition of {(,[0-9A-Z]+,)+} will be sufficient to take the HEX from above string, but instead I got the first result ",12," and not the HEX that I want. What have I done wrong ?

Upvotes: 0

Views: 302

Answers (1)

Jerry
Jerry

Reputation: 71538

You might want to use split instead:

set result [lindex [split $STRINGTOPARSE ","] 5]

regexp is not giving you the result you are looking for because the first part that matches is ,12, and the match stops there and won't look for more matches.

You could use regexp to do it, but it will be more messy... one possible way would be to match each comma:

regexp {^(?:[^,]*,){5}([0-9A-F]+),} $STRINGTOPARSE -> hex

Where (?:[^,]*,){5} matches the first 5 non-comma parts with their commas, and ([0-9A-F]+) then grabs the hex value you're looking for.


I think that the problem is that you seem to think [0-9A-Z] will have to match at least a letter, which is not the case. it will match any character within the character class and you get a match as long as you get 1 character to match.

If you wanted a regex to match a series of characters with both numbers and letters, then you would have to use some lookaheads (using classes alone might make it more messy):

regexp {\y(?=[^,A-Z]*[0-9])(?=[^,0-9]*[A-Z])[0-9A-Z]+\y} $STRINGTOPARSE -> hex

But... this might look even more complex than before, so I would advise sticking to splitting instead :)

Upvotes: 1

Related Questions