Version 3 of regsub

Updated 2002-07-30 13:14:58

http://www.purl.org/tcl/home/man/tcl8.4/TclCmd/regsub.htm


[Feel free to add various examples, demonstrating the use of the various flags, etc.]

One example of using regsub from Brent Welch's BOOK Practical Programming in Tcl and Tk is:

 regsub -- {([^\.]*)\.c} file.c {cc -c & -o \1.o} ccCmd

The & is replaced by file.c, and the \1 is replaced by file.


Recently on the Tcler's Wiki chat room, someone had the desire to convert a string like this:

 rand ||=> this is some text <=|| rand

to

 rand ||=> some other text <=|| rand


 set unique1 {\|\|=>}
 set unique2 {<=\|\|}
 set string {rand ||=> this is some text <=|| rand}
 set replacement {some other text}
 set new [regsub -- "($unique1) .* ($unique2)" $string "\\1$replacement\\2" string ]
 puts $new
 puts $string

Note that the regular expression metacharacters in unique1 and unique2 need to be quoted so they are not treated as metacharacters.


Tcl syntax help - Arts and crafts of Tcl-Tk programming - Category Command