regex - 限制 regsub 命令的数量以删除列表中的空格、行尾或回车符

标签 regex tcl

我的 list :

set myList "{ 
                {key value} {key1 value1}
                {
                    {key2 value2} {key3 value3}
                }
            }"

期望的输出:

{{key value} {key1 value1} {{key2 value2} {key3 value3}}}

到目前为止我尝试过的:

set myList  [string trim $myList]
set newList [string map {\n "" \t " "} $myList]

regsub -all {^\{\s+\{} $newList "{{"  newList ; # start of list
regsub -all {\}\s+\}$} $newList "}}"  newList ; # end of list
regsub -all {\}\s+\{}  $newList "} {" newList ; # middle of list
regsub -all {\{\s+\{}  $newList "{{"  newList ; # middle of list again
regsub -all {\}\s+\}}  $newList "}}"  newList ; # middle of list again and again

它有效,但我使用了很多 regsub 命令。 有可能限制它们吗?或不同的方法,没有 regsub...

最佳答案

首先,在 8.6 中使用 regsub 来实现这一点需要两个,其中一个绝对是丑陋的(使用前瞻):

regsub -all {(\{)\s+(?=[{}])|(\})\s+(?=\})} [regsub -all {(\})\s+(?=\{)} $myList {\1 }] {\1\2}

在 8.7 中,您可以使用 -command 选项来完成此操作(因为在某些情况下您需要不同的取代基),但 RE 本身会更难看。


您可以在不使用regsub的情况下完成此操作,但前提是您知道要规范化的深度(即逻辑结构是什么);在你的情况下,两次就足够了:

lmap item $myList {
    lmap subitem $item {
        list {*}$subitem
    }
}

命令 list {*}$thingconcat $thing 非常相似,只不过它是一个正确的列表原生命令。 concat 不是(我们有测试用例来证明这一点)。

关于regex - 限制 regsub 命令的数量以删除列表中的空格、行尾或回车符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/75132967/

相关文章:

javascript - 如何从javascript中的字符串中找出电子邮件和姓名

Tcl upvar 到另一个过程中的变量

tcl lsort 对字符串中的最后 n 个字符

tcl - 获取TCL中open创建的进程返回码

php - 用其他数组中的值替换数组中的占位符

regex - 使用正则表达式从 .log 文件中提取数据

php - 如何在 Sublime Text Build 中获取文件夹名称

javascript - 如何在javascript中组合正则表达式?

lisp - 在 Tcl 中模拟 lisp cons 单元

linux - 如何在LINUX环境下运行对象TCL?