如何从 TCL 中的 "X4/X2/X10/" 中删除 X10?

how to remove X10 from "X4/X2/X10/" in TCL?

输入是“X4/X2/X10/”。我想从中删除 X10。要求的输出是“X4/X2/”。最简单的方法是什么?

方法多种多样。这是将输入转换为片段列表的方法,使用 lsearch 对该列表进行过滤,然后重新组合结果:

set input "X4/X2/X10/"

set pieces [split $input "/"]
set removed [lsearch -inline -all -not -exact $pieces "X10"]
set output [join $removed "/"]

puts $output

what I intended was to remove the last element not specifically for X10

类似

set input "X4/X2/X10/"
set output [join [lreplace [split $input /] end-1 end-1] /]
puts $output

为此工作。

使用 string 子命令:

set input "X4/X2/X10/"

# find the index of the last slash before the end of string slash
set idx [string last / $input end-1]  ;# => 5

set new [string range $input 0 $idx]  ;# => X4/X2/

或者,一起[=13​​=]

set new [string range $input 0 [string last / $input end-1]]

我喜欢格伦在需要字符串作为输出时处理字符串精神的回答。类似的,考虑使用regexp:

% set input "X4/X2/X10/"
% regexp {(.*/)[^/]+/$} $input _ output 
% set output
X4/X2/