如何在tcl中执行子串提取和替换 [英] how to perform substring extraction and substitution in tcl
问题描述
我正在尝试从 Tcl 中的字符串中提取子字符串.我写了代码并且能够做到,但我想知道是否还有其他有效的方法来做到这一点.所以确切的问题是我有一个字符串
I am trying to extract a substring from a string in Tcl. I wrote the code and able to do it, but I was wondering if there is any other efficient way to do it. So the exact problem is I have a string
name_ext_10a.string_10a.string.string.string
我想提取name_ext
",然后删除那个_
"并将其替换为.
";我最终希望输出为name.ext
".我是这样写的:
and I want to extract "name_ext
", and then remove that "_
" and replace it with ".
"; I finally want the output to be "name.ext
". I wrote something like this:
set _File "[string replace $_File [string last "_" $_File] [string length $_File] "" ]"
set _File "[string replace $_File [string last "_" $_File] [string length $_File] "" ]"
set _File "[string replace $_File [string last "_" $_File] [string last "_" $_File] "." ]"
这给了我我想要的确切输出,但我想知道在 Tcl 中是否还有其他有效的方法可以做到这一点.
which gives me the exact output I want, but I was wondering if there is any other efficient way to do this in Tcl.
推荐答案
您可以使用下划线作为分隔符分割该文件名,然后用点连接前 2 个元素:
You could split that filename using underscore as a separator, and then join the first 2 elements with a dot:
% set f name_ext_10a.string_10a.string.string.string
name_ext_10a.string_10a.string.string.string
% set out [join [lrange [split $f _] 0 1] .]
name.ext
编辑
所以如果name"可以有任意数量的下划线:
So if "name" can have an arbitrary number of underscores:
set f "foo_bar_baz_ext_10a.string_10a.string.string.string"
set pieces [split $f _]
set name [join [lrange $pieces 0 end-3] _]
set out [join [list $name [lindex $pieces end-2]] .] ;#==> foo_bar_baz.ext
但这变得越来越复杂.一个正则表达式就足够了——我假设字符串"可以是任何非下划线字符序列.
But this is getting complex. One regex should suffice -- I assume "string" can be any sequence of non-underscore chars.
set string {[^_]+}
set regex "^(.+)_($string)_10a.${string}_10a.$string.$string.$string\$"
regexp $regex $f -> name ext
set out "$name.$ext" ;#==> foo_bar_baz.ext
这篇关于如何在tcl中执行子串提取和替换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!