|
Replacing the last comma with an and
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 $1 or \1 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 {\1 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. (written 2008-04-04 07:18:20)
Associated topics are indexed under Q803 - Object Orientation and General technical topics - Regular Expressions - Extra ElementsT205 - Tcl/Tk - String Handling in TclT206 - Tcl/Tk - Lists
Some other Articles
Learning and understanding scripting programming techniquesM25 / South Mimms Service AreaDo not SHOUT and do not whisperAutomating processes through ExpectReplacing the last comma with an andCambidge - Tcl, Expect and Perl coursesFresher tutor, better courseEvery link has two ends - fixing 404s at the recipientComparing hotels - as a guest and from the proprietors viewSelling curry to the chinese takeaway
|
2259 posts, page by page
Link to page ... 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46 at 50 posts per page
This is a page archived from The Horse's Mouth at
http://www.wellho.net/horse/ -
the diary and writings of Graham Ellis.
Every attempt was made to provide current information at the time the
page was written, but things do move forward in our business - new software
releases, price changes, new techniques. Please check back via
our main site for current courses,
prices, versions, etc - any mention of a price in "The Horse's Mouth"
cannot be taken as an offer to supply at that price.
Link to Ezine home page (for reading).
Link to Blogging home page (to add comments).
|
|