开发者

TCL - split string by arbitrary number of whitespaces to a list

Say I have a string like this:

set str "AAA    B C     DFG 142               56"

Now I want to get a list as follo开发者_Python百科ws:

{AAA B C DFG 142 56}

For that I want to use split function, but in that case I get some extra empty lists {}. How I can get the list above?


set text "Some arbitrary text which might include \$ or {"
set wordList [regexp -inline -all -- {\S+} $text]

See this: Splitting a String Into Words.


You can always do the following:

set str "AAA    B C     DFG 142               56"
set newStr [join $str " "]

It will output the following:

{AAA B C DFG 142 56}


The textutil::split module from tcllib has a splitx proc that does exactly what you want

package require textutil::split
set result [textutil::split::splitx $str]


As of Tcl 8.5, the following also works:

list {*}$str

(provided the string is also a proper list, as in the question). The output is the desired list.

Documentation: list, {*} (syntax)


I know this is old, but in case others come across this in the future I'll add my solution. I subbed the unknown number of whitespace into one character of whitespace to allow split to work correctly, similar to Scott's answer:

set str "AAA    B C     DFG 142               56"    
regsub -all { +} $str " " str ; # str is now "AAA B C DFG 142 56"
set splitout [split $str { +}] ; # Split on one or more spaces. 
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜