Remove Leading Zeros from Timestamp% j% Y% H:% M

My timestamp is in the form

0992006 09:00 

I need to remove leading zeros to get this form:

 992006 9:00 

Here is the code I'm using now that does not remove leading zeros:

 prediction$TIMESTAMP <- as.character(format(prediction$TIMESTAMP, '%j%Y %H:%M')) 
+7
date regex r
source share
6 answers
 str1 <- "0992006 09:00" gsub("(?<=^| )0+", "", str1, perl=TRUE) #[1] "992006 9:00" 

For situations like the following, this could be:

 str2 <- "0992006 00:00" gsub("(?<=^| )0", "", str2, perl=TRUE) #[1] "992006 0:00" 

Explanation

The idea here is to use look behind (?<=^| )0+ to match 0 s

if this happens either at the beginning of the line (?<=^

or |

if it follows the space )0+

and replace those that match 0s with "" in the second part of the gsub argument.

In the second line, hour and minutes all 0's . Thus, using the first code will result in:

  gsub("(?<=^| )0+", "", str2, perl=TRUE) #[1] "992006 :00" 

It is not clear what the OP will take as a result. So I thought that instead of deleting just 0 before : it would be better if only 0 remained. So, I replaced the code 0+ with one 0 and replaced it with "" .

+7
source share

The easiest way is to create your own border that claims either the beginning of a line or a space.

 gsub('(^| )0+', '\\1', '0992006 09:00') # [1] "992006 9:00" 

You can do the same thing as freeing up a replacement using a trick. \K resets the starting point of the reported match, and all previously used characters are no longer included.

 gsub('(^| )\\K0+', '', '0992006 09:00', perl=T) # [1] "992006 9:00" 

Or you can use sub and match up to a second set of leading zeros.

 sub('^0+([0-9]+ )0+', '\\1', '0992006 09:00') # [1] "992006 9:00" 

And to cover all the possibilities, if you know that you will ever have a format like 0992006 00:00 , just remove the quantifier + from scratch in the regular expression so that it only removes the first leading zero.

+8
source share

Here is another option using lookbehind

 gsub("(^0)|(?<=\\s)0", "", "0992006 09:00", perl = TRUE) ## [1] "992006 9:00" 
+7
source share

With sub :

  sub("^[0]+", "", prediction$TIMESTAMP) [1] "992006 09:00" 
+2
source share

You can also use stringr without regex using substrings.

 > library(stringr) > str_c(str_sub(word(x, 1:2), 2), collapse = " ") # [1] "992006 9:00" 
+1
source share

A few additional Perl regular expressions,

 > gsub("(?<!:)\\b0+", "", "0992006 09:00", perl=T) [1] "992006 9:00" > gsub("(?<![\\d:])0+", "", "0992006 09:00", perl=T) [1] "992006 9:00" 
+1
source share

All Articles