为什么我的变量中的特殊字符在 TCL 中执行 lindex 时消失了



我的应用程序中有一个我正在处理的列表。它基本上是这样的:

$item = {text1 text2 text3}

然后我选择列表中的第一个成员:

lindex $item 0

在做这个文本1时,曾经是(说(abcdef12345变得abcdef12345.但对我来说,不要失去这个非常重要.为什么它会消失。还有其他角色,如->不会消失。 请注意,我无法事先逃脱文本中的。如果在与lindex一起在$item上手术之前我能做些什么,请提出建议。

问题是是一个Tcl列表元语法字符,不像->或任何字母数字。您需要先将字符串转换为适当的 Tcl 列表,然后再对其使用 lindex(或任何其他列表消耗操作(。为此,您需要准确理解输入数据中"单词"的含义。如果输入数据是由单个空格字符分隔的非空格字符序列,则可以使用 split 将转换为列表:

set properList [split $item]
# Now we can use it...
set theFirstWord [lindex $properList 0]

如果您有不同的分隔符,split会使用一个可选的额外字符来表示要拆分的内容。例如,要按冒号(:(拆分,您可以执行以下操作:

set properList [split $item ":"]

但是,如果您有其他类型的拆分规则,则效果不佳。例如,如果可以拆分多个空格字符,实际上最好使用 regexp(带有-all -inline选项(进行单词识别:

# Strictly, this *chooses* all sequences of one or more non-whitespace characters
set properList [regexp -all -inline {S+} $item]
您也可以按多字符序列

进行拆分,但在这种情况下,最容易完成的是先将多字符序列映射到单个稀有字符(string map(。Unicode 意味着有很多这样的字符可供选择......

# NUL, u0000, is a great character to pick for text, and terrible for binary data
# For binary data, choose something beyond u00ff
set properList [split [string map {"BOUNDARY" "u0000"} $item] "u0000"]

更复杂的选项是可能的,但那是当你使用Tcllib的splitx的时候。

package require textutil::split
# Regular expression to describe the separator; very sophisticated approach
set properList [textutil::split::splitx $item {SPL+I*T}]

在 tcl 中,可以通过多种方式创建列表:

通过将变量设置为值列表

set lst {{item 1} {item 2} {item 3}} 

使用拆分命令

set lst [split "item 1.item 2.item 3" "."] 

使用列表命令。

set lst [list "item 1" "item 2" "item 3"] 

并且可以使用 lindex 命令访问单个列表成员。

set x "a b c"
puts "Item 2 of the list {$x} is: [lindex $x 2]n"

这将给出输出:

Item 2 of the list {a b c} is: c

关于提出的问题您需要像这样定义变量abcdef\12345

为了明确这一点,请尝试运行以下命令。

puts "nI gave $100.00 to my daughter."

puts "nI gave $100.00 to my daughter."

第二个会给你正确的结果。

如果您没有更改文本的选项,请尝试将文本保存在大括号中,如第一个示例中所述。

set x {abcd12345}
puts "A simple substitution: $xn"

输出:

A simple substitution: abcd12345
set y [set x {abcdef12345}]

并检查此输出:

puts "Remember that set returns the new value of the variable: X: $x Y: $yn"

输出:

Remember that set returns the new value of the variable: X: abcdef12345 Y: abcdef12345

最新更新