从R中给定的字符串中提取日期 [英] Extract date from a given string in R
本文介绍了从R中给定的字符串中提取日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这是我拥有的一个字符串
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")
我为此不适用.
所需的输出为
2013-08-21
有人可以指出我正确的方向吗?
Can someone point me in the right direction?
推荐答案
您已在正则表达式中将破折号-
替换为斜线/
.
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"
但是您也可以将[0-9]
位替换为\d
,它们代表同一件事.我不确定为什么,但是正则表达式专业人士似乎总是使用\d
版本(请注意,您必须使用另一个反斜杠来转义反斜杠):
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"
这篇关于从R中给定的字符串中提取日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文