我有一个要替换的十六进制字符串。
Hello %user and %user2
在这种情况下,我要用填充的变量结果Willma和Fred替换%user和%user2。
在哪里使用标签%user和%user2都表示相同的十六进制值,它们都被替换为“ Willma”。我如何对一组十六进制字符进行精确替换?
我正在使用的代码:
set example "48656c6c6f20257573657220616e6420257573657232" ;# Hello %user and %user2 converted to hex
set modify [list "2575736572" "Willma"] ;#replace the tagSymbol as defined from the single entry %user1 | %user2
set hexData [string map $modify $example] ;#preform the swap
%user 以十六进制 2575736572 表示。 32 是数字2的十六进制值。下一个十六进制字符串变为 257573657232
但是,当我执行字符串映射时,它会根据设计交换%user2 ,而保留 32 。但是,这不是我想要的。以下是我要寻找的东西。
最终输出:
48656c6c6f20Willma20616e6420Willma32
当我想要的时候
48656c6c6f20Willma20616e6420257573657232
我将如何进行精确交换? 谢谢
答案 0 :(得分:1)
string map
映射中的替换顺序很重要。特别是,在每个字符位置,它都会在地图中进行 first 转换,然后在该点不再应用任何其他转换。这意味着%user2
被%user
屏蔽,除非它先行。 (通常,如果您想找出自动顺序,只需按长度排序所有起始值,然后是最长的最长排序。 Tcl不会为您执行此操作。在大多数情况下,{{1 }},则屏蔽效果无关紧要,或者在源代码级别的排序是可行的。)
string map
请注意,我在那里使用了set example "48656c6c6f20257573657220616e6420257573657232"
set modify {}
lappend modify [binary encode hex "%user2"] "Fred"
lappend modify [binary encode hex "%user"] "Willma"
set hexData [string map $modify $example]
# ==> 48656c6c6f20Willma20616e6420Fred
。这是Tcl 8.6的功能;如果您使用的是较旧的Tcl,则需要以下帮助程序:
binary encode hex