« What is Expect? | Main | Buffering of inputs to expect, and match order »

October 27, 2007

Tcl / regsub - changing a string and using interesting bits

Regexp 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 \1, \2, etc, if I wish.

Example:

# In Tcl,
# regub needle haystack newneedle saveithere
#
# Refer to matches in the newneedle via \1
# Example - to surround dogs, cats and rabbits with !s
#
regsub -all (cat|dog|rabbit) "The cat and dog and budgie" \
  {!\1!} 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$

Posted by gje at October 27, 2007 07:05 AM

Comments

Post a comment




Remember Me?


Well House Consultants Ltd. Copyright 2008