TCL 字符串映射精确值
tcl string map exact values
我有一个转换后的十六进制字符串,我想替换它。
Hello %user and %user2
我想用填充的变量结果替换 %user 和 %user2,在这种情况下,Willma 和 Fred。
在我使用标签 %user 和 %user2 的地方,它们都代表相同的十六进制值,它们都被替换为 "Willma" 我怎样才能进行 exact 替换一组十六进制字符?
我使用的代码:
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
我将如何进行精确交换?
谢谢
string map
映射中的替换顺序很重要。特别是,在每个字符位置,它在地图中执行 first 变换,然后不在该点应用任何进一步的变换。这意味着 %user2
会被 %user
掩盖,除非它先出现。 (一般来说,如果你想找出一个自动顺序,只需按长度对所有 from-values 进行排序,最长的在前。Tcl 不会为你做这个。 在大多数情况下在使用 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
请注意,我在那里使用了 binary encode hex
。这是 Tcl 8.6 的一个特性;如果您使用的是较旧的 Tcl,则需要这个小帮助程序:
proc HexOf {str} {
binary scan $str H* hexdigits
return $hexdigits
}
我有一个转换后的十六进制字符串,我想替换它。
Hello %user and %user2
我想用填充的变量结果替换 %user 和 %user2,在这种情况下,Willma 和 Fred。
在我使用标签 %user 和 %user2 的地方,它们都代表相同的十六进制值,它们都被替换为 "Willma" 我怎样才能进行 exact 替换一组十六进制字符?
我使用的代码:
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
我将如何进行精确交换? 谢谢
string map
映射中的替换顺序很重要。特别是,在每个字符位置,它在地图中执行 first 变换,然后不在该点应用任何进一步的变换。这意味着 %user2
会被 %user
掩盖,除非它先出现。 (一般来说,如果你想找出一个自动顺序,只需按长度对所有 from-values 进行排序,最长的在前。Tcl 不会为你做这个。 在大多数情况下在使用 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
请注意,我在那里使用了 binary encode hex
。这是 Tcl 8.6 的一个特性;如果您使用的是较旧的 Tcl,则需要这个小帮助程序:
proc HexOf {str} {
binary scan $str H* hexdigits
return $hexdigits
}