Main Content

Replacing the last comma with an and

Archive - Originally posted on "The Horse's Mouth" - 2008-04-04 07:18:20 - Graham Ellis

If I have a list, I'm likely to want to present it comma separated for the most part, but with the word "and" between the last two elements.

"Cambridge, the M11, the M25, the M4, the A361 and Melksham" for example.

Lists or arrays can be joined in almost any language with a function called join or implode, and a parameter will allow you to specify that comma. But what about the "and"? A regular expression looking for a comma and replacing it with an "and" would just replace the FIRST comma. Solution - use a greedy "match anything" element at the start of the regular expression, thus matching the last comma. You can refer to or in your replacement string.

Want to see an example of that in use? Here is the algorithm coded in Tcl

set codez {SWI CPM MKM TRO WSB DMH WAR SAL}
puts $codez
set togo [join $codez ", "]
regsub {(.*),} $togo { and} togo
puts $togo


And here is how it runs

Dorothy:mt2 grahamellis$ tclsh fbl
SWI CPM MKM TRO WSB DMH WAR SAL
SWI, CPM, MKM, TRO, WSB, DMH, WAR and SAL
Dorothy:mt2


Example written as a demonstration for delegates on the Tcl and Expect course I am running at the moment.