从R中的字符串中提取带有子子串的模式

Lea*_*Liu 0 regex substring r date pattern-matching

我有一组像

data <- c("ABS Spring Meeting 5.14.15", "DEFG Sellors Tour 10.28.14", "DDCC Fun at the Museum 4.4.15", "GAME CS vs. Washington 11.01.14", "BSS Studio 54 5.13.15","Pas-12 3.5.15")
Run Code Online (Sandbox Code Playgroud)

您可以注意到,最后一组数字是事件日期.我想把它们转换成日期

date <- c("2015-05-14","2014-10-28","2015-04-04","2014-11-01","2015-05-13","2015-03-05")
Run Code Online (Sandbox Code Playgroud)

感觉我必须将这种类型("5.14.15","10.28.14","4.4.15","11.01.14","5.13.15","3.5.15")子串到子模式,然后做转换日期.

谁能帮我这个?谢谢!

Ric*_*ven 5

在基数R中,如果日期始终位于字符串的末尾,则可以使用

as.Date(sub(".*\\s", "", data), "%m.%d.%y")
# [1] "2015-05-14" "2014-10-28" "2015-04-04" "2014-11-01"
Run Code Online (Sandbox Code Playgroud)

这里,正则表达式很简单

  • .* 一切
  • \\s 空间角色

因此,这将删除所有内容,包括最终的空格字符.