Search code examples
stringtclspecial-characters

delete part of string (word) in tcl


In Tcl I have some variable (string) witch are come from some input text file. They are too many... Some thing look like what you are going to faced over :

 A1 = LP89slc.AT271300.0
 A2 = LP89slc.AT28742.0
 A3 = LP89slc.AT2-71300.0
 A3 = LP89slc.AT2-0.260-0.085

All of them have the same part in the meddle of the string ({...}+{.AT2}+{...}) ==> (.AT2) I want to delete a right part that come next of the (.AT2) for example :

A1 = LP89slc.AT271300.0  ==> LP89slc.AT2
A2 = LP89slc.AT2-71300.0 ==> LP89slc.AT2

Also I want to know is there a way that I can delete the last part of a string that come next to the special character like ...At2... for example : after set unpredictable variable like {SomeCharecter.At2UndesirablePart} change it to the {SomeCharecter.At2}

The difference between this question and first one is that, in first situation, first part is finite and assignable. but in second question both part that come in left and right place of {AT2} are unpredictable.

trim trimright trimleft commands dont do my job!


Solution

  • The easiest way is to use a regular expression substitution:

    regsub -all -line {^.*\y(\w+\.AT2).*$} $theString {\1} theString
    

    The tricky bits here are the -line option (which makes this work when applied to a multi-line string) and the \y in the regular expression (which matches at the start or end of a word — it's the start in this case because a \w must match next).