Using Tcl string map

The string commands have been optimized for performance.

For finding and replacing characters or strings, string map is the most efficient method.

Unless you must find and replace a string based on a pattern, using string map is more efficient than regsub.

set var "000-111-2222"
regsub -all -- {\-} $var "" var
puts $var ;# Returns "0001112222"
set var "000-111-2222"
set var [string map {- {}} $var]
puts $var ;# Returns "0001112222"

The string map command is simpler to use with special characters and escapes. In the example above, the dash has to be escaped in the regsub, but not in the string map.

This is an example using string map with multiple pairs:

set map [list               \
    |  \\F                           \
    ^  \\S                           \
    \\ \\E                           \
    &  \\T                           \
    ~  \\R                           \
    \r \\X0D\\\\X0A\\                \
    \n \\X0A\\                       \
]
set var [string map $map $var]