Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove prefix substring from string

Tags:

tcl

I have a string abc.def.ghi.j and I want to remove abc. from that, so that I have def.ghi.j.

1) What would be the best approach to remove such a prefix which has a specific pattern?

2) Since in this case, abc is coincidentally the prefix, that probably makes things easier. What if we wanted abc.ghi.j as the output?

I tried it with the split method like this

set name abc.def.ghi.j
set splitVar [split $name {{abc.}} ]

The problem is that it splits across each of a, b, c and . seperately instead of as a whole.

like image 996
sbhatla Avatar asked Sep 20 '25 06:09

sbhatla


1 Answers

Well, there's a few ways, but the main ones are using string replace, regsub, string map, or split-lreplace-join.

We probably ought to be a bit careful because we must first check if the prefix really is a prefix. Fortunately, string equal has a -length operation that makes that easy:

if {[string equal -length [string length $prefix] $prefix $string]} {
    # Do the replacement
}

Personally, I'd probably use regsub but then I'm happy with using RE engine tricks.

Using string replace

set string [string replace $string 0 [string length $prefix]-1]
# Older versions require this instead:
# set string [string replace $string 0 [expr {[string length $prefix]-1}]]

Using regsub

# ***= is magical and says "rest of RE is simple plain text, no escapes"
regsub ***=$prefix $string "" string

Using string map

# Requires cunning to anchor to the front; \uffff is unlikely in any real string
set string [string map [list \uffff$prefix ""] \uffff$string]

Using splitjoin

This is about what you were trying to do. It depends on the . being a sort of separator.

set string [join [lrange [split $string "."] 1 end] "."]
like image 183
Donal Fellows Avatar answered Sep 21 '25 23:09

Donal Fellows