简体   繁体   English

从字符串解析十六进制值

[英]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" 我正在尝试从条件为“ 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. 我相信{(,[0-9A-Z] +,)+}的条件足以从上面的字符串中提取HEX,但是我得到的第一个结果是“,12”,而不是我想要的HEX 。 What have I done wrong ? 我做错了什么?

You might want to use split instead: 您可能要改用split:

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. regexp不能为您提供所需的结果,因为匹配的第一部分是,12,并且匹配项在那里停止并且不会寻找更多匹配项。

You could use regexp to do it, but it will be more messy... one possible way would be to match each comma: 您可以使用regexp来做到这一点,但是会更加混乱……一种可能的方式是匹配每个逗号:

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. 其中(?:[^,]*,){5}将前5个非逗号部分与其逗号匹配,然后([0-9A-F]+)捕获您要查找的十六进制值。


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. 我认为问题在于您似乎认为[0-9A-Z]必须至少匹配一个字母,事实并非如此。 it will match any character within the character class and you get a match as long as you get 1 character to match. 它会匹配字符类中的任何字符,并且只要有1个字符可以匹配就可以匹配。

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 :) 但是...这看起来可能比以前更复杂,所以我建议改用分割法:)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM