Skip to content

Regex to remove last character

4 messages · rivercode, David Winsemius, Henrique Dallazuanna +1 more

#
Hi,

Have been having trouble trying to figure out the right regex parameters to
remove the last "." in timestamp with the following format:

Convert 09:30:00.377.853 to  09:30:00.377853

Thanks,
Chris
#
On Jan 3, 2011, at 2:24 PM, rivercode wrote:

            
gsub("()(\\.)(.{3}$)", "\\1\\3" , "09:30:00.377.853")
[1] "09:30:00.377853"
==

David Winsemius, MD
West Hartford, CT
#
On 01/03/2011 02:44 PM, David Winsemius wrote:
The 'g' in 'gsub' says 'make multiple substitutions in a single
character element' (compare gsub("0", "o", "09:30:00.377.853") with
sub("0", "o", "09:30:00.377.853")) whereas here there's just a single
substitution per character string ('.' with ''). Maybe

  sub("\\.([[:digit:]]+)$", "\\1", "09:30:00.377.853")

where the pattern is 'a literal period \\. followed by 1 or more digits
[[:digits:]]+ followed by an end-of-record $', with the 1 or more digits
remembered as \\1 for the replacement.

The [:digit:] is explained in ?regex; a less thorough solution would use
"\\.(\\d+)$".

Martin