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
...
CodePudding user response:
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 (i.e., 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).
CodePudding user response:
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}}}