Search code examples
regextclregsub

In Tcl how can I remove all zeroes to the left but the zeroes to the right should remain?


Folks! I ran into a problem that I can't solve by myself.

Since the numbers "08" and "09" cannot be read like the others (01,02,03,04, etc ...) and must be treated separately in the language Tcl.

I can't find a way to remove all [I say ALL because there are more than one on the same line] the leading zeros except the one on the right, which must remain intact.

It may sound simple to those who are already thoroughly familiar with the Tcl / Tk language. But for me, who started out and am looking for more information about Tcl / Tk, I read a lot of material on the internet, including this https: // stackoverflow.com/questions/2110864/handling-numbers-with-leading-zeros-in-tcl#2111822 So nothing to show me how to do this in one sweep eliminating all leading zeros.

I need you to give me a return like this: 2:9:10

I need this to later manipulate the result with the expr [arithmetic expression] command.

In this example it just removes a single leading zero:

set time {02:09:10}
puts [regsub {^0*(.+)} $time {\1}]
# Return: 2:09:10

If anyone can give me that strength friend?! I'm grateful right now.


Solution

  • The group (^|:) matches either the beginning of the string or a colon. 0+ matches one or more zeros. Replace with the group match \1, otherwise the colons get lost. And of course, use -all to do all of the matches in the target string.

    % set z 02:09:10
    02:09:10
    % regsub -all {(^|:)0+} $z {\1} x
    2
    % puts $x
    2:9:10
    % 
    

    Edit: As Barmar points out, this will change :00 to an empty string. A better regex might be:

    regsub -all {(^|:)0} $z {\1} x
    

    This will only remove a single leading 0.