list TCL - 将字符串按任意数量的空格拆分为列表

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5728656/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-11 01:38:32  来源:igfitidea点击:

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

listsplitwhitespacetcl

提问by Narek

Say I have a string like this:

假设我有一个这样的字符串:

set str "AAA    B C     DFG 142               56"

Now I want to get a list as follows:

现在我想得到一个列表如下:

{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?

为此,我想使用 split 函数,但在这种情况下,我会得到一些额外的空列表 {}。我如何获得上面的列表?

回答by ba__friend

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

See this: Splitting a String Into Words.

请参阅:将字符串拆分为单词

回答by Scott

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}

回答by glenn Hymanman

The textutil::splitmodule from tcllibhas a splitxproc that does exactly what you want

来自tcllibtextutil::split模块有一个完全符合你要求的过程splitx

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

回答by Peter Lewerin

As of Tcl 8.5, the following also works:

从 Tcl 8.5 开始,以下内容也有效:

list {*}$str

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

(前提是字符串也是一个正确的列表,如问题所示)。输出是所需的列表。

Documentation: list, {*} (syntax)

文档: list, {*} (语法)

回答by Ryan

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:

我知道这是旧的,但如果其他人将来遇到这个问题,我会添加我的解决方案。我将未知数量的空格替换为一个空格字符以允许拆分正常工作,类似于 Scott 的回答:

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 { +}]