Main Content

Regular Expression Substitution - Tcl

Archive - Originally posted on "The Horse's Mouth" - 2013-11-12 12:00:31 - Graham Ellis

regexp matches regular expressions in TCL, and it will return the latest match into a series of variables if you specify their names. regsub matches and replaces... not quite such a common requirement, and perhaps something I haven't blogged about in the past.

  set newstory [regsub blue $original grey]
Take the string from $original, replace the first occurrence of blue with grey and return the resulting string - which I have saved into a variable called new story

I can replace all occurrences of blue using the -all option:
  set newstory [regsub -all blue $original grey]

and I can use part of the incoming search as part of the outgoing string too. In this example:
  set newstory [regsub -all {bl(\S+)} $original br\1]
I have taken all words with "bl" in them and replaces the bl and the rest of the word with br and the rest of the word as it was incoming. Note the capture using round brackets, and the back reference on output to \1 for the first captured set of brackets. This example changes:
  It was a clear blue day and he blew into her blue eyes
into
  It was a clear brue day and he brew into her brue eyes

Full example in source code [here]

As taught on last week's Learning to program in Tcl course. This is a public course which runs every few months; the recent one was the final run for 2013, but you can find future dates for 2014 and beyond [here] on our web site.