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.
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.
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}]]
regsub
# ***= is magical and says "rest of RE is simple plain text, no escapes"
regsub ***=$prefix $string "" string
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]
split
…join
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] "."]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With