Tcl / regsub - changing a string and using interesting bits
Archive - Originally posted on "The Horse's Mouth" - 2007-10-27 07:05:28 - Graham EllisRegexp matches a string to a regular expression, and regsub goes one further in that it replaces the found string with something else, saving the transformed output into a new variable. But what if I want the output pattern to include part of the string that was matched? I can refer to the "interesting bits" using , , etc, if I wish.
Example:
# In Tcl,
# regub needle haystack newneedle saveithere
#
# Refer to matches in the newneedle via
# Example - to surround dogs, cats and rabbits with !s
#
regsub -all (cat|dog|rabbit) "The cat and dog and budgie" \
{!!} result
puts $result
Results:
earth-wind-and-fire:~/oct07/camb grahamellis$ tclsh rsd
The !cat! and !dog! and budgie
earth-wind-and-fire:~/oct07/camb grahamellis$