Version 4 of regmap

Updated 2003-10-31 17:51:11

A function to substitute parts of a string matching a regular expression with the result of a script called using the match as argument. Code and examples will be much more clear then my english:

    proc regmap {re string script} {
        set submatches [lindex [regexp -about $re] 0]
        lappend varlist idx
        while {[incr submatches -1] >= 0} {
            lappend varlist _
        }
        set res $string
        set indices [regexp -all -inline -indices $re $string]
        set delta 0
        foreach $varlist $indices {
            foreach {start end} $idx break
            set substr [string range $string $start $end]
            set toeval [string map [list %s $substr] $script]
            set subresult [eval $toeval]
            incr start $delta
            incr end $delta
            set res [string replace $res $start $end $subresult]
            incr delta [expr {[string length $subresult]-[string length $substr]}]
        }
        return $res
    }

Example:

 puts [regmap {[0-9]+} "1 20 hello 30 how are you 40" {expr %s+1}]
 puts [regmap {[a-z]+} "My name is merz" {format "%s([string length %s])"}]

The output is the following:

 2 21 hello 31 how are you 41
 My(1) name(4) is(2) merz(4)

Note that you can use regsub and subst combined to get the same effect, but often it is less secure (against non truested inputs) and usually more tricky.

Comments to SS