how to perform substring extraction and substitution in tcl

string, tcl

Solution

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

EDIT

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

Problem

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` 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] "." ]" ``` which gives me the exact output I want, but I was wondering if there is any other efficient way to do this in Tcl.

Original source