Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extract date from a given string in R

Tags:

datetime

r

gsub

Here is a string that I have

"7MA_S_VE_MS_FB_MEASURE_P1_2013-08-21_17-42-19.BMP"

I am trying to extract dates this way:

library(stringr)
as.Date(str_extract(test,"[0-9]{4}/[0-9]{2}/[0-9]{2}"),"%Y-%m-%d")

I am getting NA for this.

Desired output is

2013-08-21

Can someone point me in the right direction?

like image 580
Sharath Avatar asked Dec 13 '25 17:12

Sharath


1 Answers

You have replaced your dash - with a slash / in your regular expression.

as.Date(str_extract(string, "[0-9]{4}-[0-9]{2}-[0-9]{2}"), format="%Y-%m-%d")
# [1] "2013-08-21"

But you can also replace the [0-9] bits with \d, which represent the same thing. I'm not sure why, but regex pros seem to always use the \d version (note that you'll have to escape the backslash with another backslash):

as.Date(str_extract(string, "\\d{4}-\\d{2}-\\d{2}"), format="%Y-%m-%d")
# [1] "2013-08-21"
like image 112
KenHBS Avatar answered Dec 16 '25 10:12

KenHBS



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!