This is the new home of the egghelp.org community forum.
All data has been migrated (including user logins/passwords) to a new phpBB version.


For more information, see this announcement post. Click the X in the top right-corner of this box to dismiss this message.

Using regexp to insert commas into date string

Old posts that have not been replied to for several years.
Locked
M
Moo_Moo

Using regexp to insert commas into date string

Post by Moo_Moo »

Let's assume I have a variable called 'time' whose value is '63 days 4 hours 28 minutes' and I want to insert a comma after every word without a preceding number. I wrote a small procedure to do the trick, but it is messy and rather cpu intensive, so I figured I'd use regular expressions instead. My problem is, despite hours of studying various regexp- manuals and tutorials, that I can't figure out how. This is how I want the string to look after formatting it: "63 days, 4 hours, 28 minutes"

The procedure, which simply scans through the string given, checks if the previous character was not a number and if the current character is an empty space, inserts a comma, looks like this:

Code: Select all

proc fixtime {time} {
   set p ""
   set r ""
   foreach c [split $time ""] {
      if {![string is integer $p] && [string equal " " $c]} {
         append r ,
      }
      append r $c
      set p $c
   }
   return $r
}
So, does anyone a little more experienced using regular expressions know how I could go on about this? If so, I'd appreciate it if you would share your knowledge with me. I've spent too many hours trying and failing to do anything else. Thanks in advance.
User avatar
strikelight
Owner
Posts: 708
Joined: Mon Oct 07, 2002 10:39 am
Contact:

Post by strikelight »

You are correct in saying regular expressions, however incorrect in wanting to use "regexp" for the task. You will want to use regsub for the job using regular expressions...

ie.

Code: Select all

regsub -all {([^0-9]) } $text {\1, } text
The "([^0-9]) " matches any non-numeric character before a space,
the \1 says you still want that character but place a comma and space after it....
M
Moo_Moo

regexp/regular expressions

Post by Moo_Moo »

Ah, thanks. That did the trick. And when saying 'regexp' I refered to 'regular expressions' - I knew what I needed was regsub. :mrgreen:
Locked