Re: string trim



On Tue, 13 May 2008 18:02:06 +0200,
Ralf Fassel <ralfixx@xxxxxx> wrote:

* gtb <goodTweetieBird@xxxxxxxxxxx>
| Was hoping someone had an expression for trimming off the first
| space and everything thereafter. I have a string like:
| powerLevel = 60;
# discard whitespace at start
set string [string trimleft $string]
# search first space
set first [string first { } $string]
# if found, discard everything after it
if {$first > 0} {
# note: first space can't be at pos 0 due to trimleft
set string [string range $string 0 [expr {$first-1}]]
}

set first [lindex [split [string trimleft $string]] 0]

I like to have that [split] in there to protect [lindex] from any
malformed lines that might slip through. Another variant that I'm
rather fond of (although I've never bothered to worry about it
performance-wise) is:

set words [lsearch -all -inline -not [split $string] {}]
set first [lindex $words 0]

Again, [string trim?left?] helps quickly cut off leading (and/or
trailing) whitespace, it then splits it, and ditches any empty items
caused by multiple consecutive spaces. Although, for that purpose;

set words [regexp -all -inline {\S+}]

works rather well also... And again, then it's just a case of plucking
off the first word. (I do rather wish [split] had the option to skip
consecutive separator characters...!)


Other than that, I'd use a regexp :-)
regsub { *=.*} [string trimleft $string] {} string

regexp {([^=]+)=(.*)} $string -> item value

and then use [string trim] on each to remove the white space. You can,
of course, fancy it up to trim off the white space for you, but getting
rid of the space just before the equal sign, and at the end of the line,
can be tricky (mixing greediness and the likes). So it's easier just
to split the line around the equal sign (that [^=]+ stuff will split it
at the FIRST equal sign, instead of the LAST which would be the default
otherwise). Of course, in that case you could also do;

set rest [join [lassign [split $string =] first] =]

and if you want, combine that with the [lindex] and/or [string
trim]ming... And that's just the basic stuff.


Fredderic
.