【问题标题】:How to convert %hex to chars in Tcl?如何在 Tcl 中将 %hex 转换为字符?
【发布时间】:2021-09-05 13:40:59
【问题描述】:

我需要 TCL 方面的帮助。我以以下字符串为例:

%3Cdiv%20id%3D%22video-container-direct%22%20style%3D%22position%3A%20relative%3Bpadding-bottom%3A%2056.6%25%3Bpadding-top%3A%2090px
%3Bheight%3A%200%3Boverflow%3A%20hidden%3B%22%3E%3Ciframe%20allowfullscreen%3D%22%22%20frameborder%3D%220%22%20scrolling%3D%E2%80%9Cno
%22%20src%3D%22%2F%2Fwww.vsports.pt%2Fembd%2F68680%2Fm%2F8856%2Fmaisf%2Fce1702fde64b1cf799dded7f1f3ab428%3Fautostart%3Dfalse%22%20
style%3D%22position%3A%20absolute%3Btop%3A0%3Bleft%3A%200%3Bwidth%3A%20100%25%3Bheight%3A%20100%25%3Bborder%3A0%22%3E%3C%2Fiframe
%3E%3C%2Fdiv%3E

我想替换 % 之后的所有内容并删除 % 当然。我的意思是,将%2F 转换为/,将%3D 转换为=,等等。

【问题讨论】:

    标签: string char hex tcl


    【解决方案1】:

    简单的方法是使用来自tclliburi::urn 包(应该可以通过操作系统的包管理器安装):

    #!/usr/bin/env tclsh
    
    package require uri::urn
    
    set s "%3Cdiv%20id%3D%22video-container-direct%22%20style%3D%22position%3A%20relative%3Bpadding-bottom%3A%2056.6%25%3Bpadding-top%3A%2090px
    %3Bheight%3A%200%3Boverflow%3A%20hidden%3B%22%3E%3Ciframe%20allowfullscreen%3D%22%22%20frameborder%3D%220%22%20scrolling%3D%E2%80%9Cno
    %22%20src%3D%22%2F%2Fwww.vsports.pt%2Fembd%2F68680%2Fm%2F8856%2Fmaisf%2Fce1702fde64b1cf799dded7f1f3ab428%3Fautostart%3Dfalse%22%20
    style%3D%22position%3A%20absolute%3Btop%3A0%3Bleft%3A%200%3Bwidth%3A%20100%25%3Bheight%3A%20100%25%3Bborder%3A0%22%3E%3C%2Fiframe
    %3E%3C%2Fdiv%3E"
    
    puts [uri::urn::unquote $s]
    

    Tcl 8.7 将允许您使用regsub 来实现(URL 解码甚至是示例之一,复制如下):

    # Match one of the sequences in a URL-encoded string that needs
    # fixing, converting + to space and %XX to the right character
    # (e.g., %7e becomes ~)
    set RE {(\+)|%([0-9A-Fa-f]{2})}
    
    # Note that -command uses a command prefix, not a command name
    set decoded [regsub -all -command $RE $string {apply {{- p h} {
        # + is a special case; handle directly
        if {$p eq "+"} {
            return " "
        }
        # convert hex to a char
        scan $h %x charNumber
        format %c $charNumber
    }}}]
    
    puts $decoded
    

    【讨论】:

    • 这正是我要给出的答案。在 8.7 之前进行解码是 messyregsubsubst 的混乱,在编写时总是需要仔细测试),所以最好使用库函数。
    • 感谢所有回复。我目前在树莓派上运行 raspbian 10.9。 tcl 的当前版本是 8.6.9。我想我尝试使用其他机器手动安装 tcl 8.6.11 或 tcl 8.7 alpha,但安装不如我使用 apt-get 安装那么完美,所以我决定坚持使用稳定版本中包含的 tcl 8.6.9与Debian。至于我的问题的解决方案,包 require urn::uri 效果很好。它说 1.0.3 并解码了乱码。谢谢。
    猜你喜欢
    • 1970-01-01
    • 2018-03-20
    • 2018-07-11
    • 2016-08-28
    • 2021-11-17
    • 1970-01-01
    • 2020-11-13
    • 1970-01-01
    • 2019-12-27
    相关资源
    最近更新 更多