Extract date from a given string in R

醉酒当歌 提交于 2020-02-25 05:03:47

问题


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?


回答1:


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"



回答2:


If it as fixed position

as.Date(strsplit(str1, "_")[[1]][8])
#[1] "2013-08-21"


来源:https://stackoverflow.com/questions/46528912/extract-date-from-a-given-string-in-r

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!