简体   繁体   中英

limit the numbers of regsub commands to delete spaces, end of line or carriage return in list

My list:

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

Desired output:

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

What I've tried so far:

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

It works, but I've used many regsub command. Is it possible to limit them? or a different approach, without regsub ...

First off, doing it with regsub in 8.6 requires two, where one of them is decidedly ugly (using lookaheads):

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

In 8.7, you can do it with one using the -command option (because you need the different substituent in some cases) but the RE itself will be uglier.


You can do it without regsub , but only if you know how deep you want to normalize (ie, what the logical structure is); in your case, twice is enough:

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

The command list {*}$thing is rather like concat $thing except that it is a proper list-native. concat isn't (and we have the test cases to prove it).

This removes leading/trailing whitespace from each line and also newlines

regsub -all -line {(^\s+)|(\s+$)|\n} $myList ""
# => {{key value} {key1 value1}{{key2 value2} {key3 value3}}}

It does remove the space between sublists though.

regsub -all -line {(^\s+)|(\s+$)|\n} $myList "" flattened
regsub -all {\}\{} $flattened "} {"
# => {{key value} {key1 value1} {{key2 value2} {key3 value3}}}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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