r - 从R中的字符串中提取混合日期

标签 r gsub stringr tidytext

我有一个字符向量,如下表所示,我想从中提取日期并将它们转换为 as.Date。例如,第一行是 09-11-2021。字符串中的最后一个数字是列数而不是日期的一部分。

   <chr>                                                                       
 1 By Leigh-Ann Butler, Shannon Cobb, Michael R. DonaldsonNov 9, 20213 Comments
 2 By Leigh-Ann Butler, Shannon Cobb, Michael R. DonaldsonNov 8, 20212 Comments
 3 By Rick AndersonNov 4, 202114 Comments                                      
 4 By Victoria Ficarra, Rob JohnsonNov 3, 20215 Comments                       
 5 By Roger C. SchonfeldNov 1, 202123 Comments                                 
 6 By Joseph EspositoOct 29, 20211 Comment                                     
 7 By Brigitte ShullOct 20, 20216 Comments                 
example.data <- c("By Leigh-Ann Butler, Shannon Cobb, Michael R. DonaldsonNov 9, 20213 Comments",
"By Leigh-Ann Butler, Shannon Cobb, Michael R. DonaldsonNov 8, 20212 Comments",
"By Rick AndersonNov 4, 202114 Comments",                                      
"By Victoria Ficarra, Rob JohnsonNov 3, 20215 Comments")

最佳答案

你可以使用

as.Date(gsub(".+(\\w{3}\\s\\d{1,2},\\s\\d{4}).*", "\\1", example.data), format = "%b %d, %Y")

#> [1] "2021-11-09" "2021-11-08" "2021-11-04" "2021-11-03"

关于r - 从R中的字符串中提取混合日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74931487/

相关文章:

r - 根据 R 中的模式集合提取数字

r - 在R中将多页pdf的每一页转换为单独的png文件

html - 从网球运动员事件页面读取所有 html 表

r - R:如何将数据帧值缩短为第一个字符

r - 使用 R 中的 str_count 计算整个单词/数字的出现次数

r - 如果函数源自 R,Stringi/stringr 模式的行为会有所不同

r - 列出 R Shiny 服务器上应用程序中的对象内存使用情况

r - XTS 替换错误 NextMethod(.Generic) : number of items to replace

ruby-on-rails - Ruby gsub 不替换换行符

ruby - 使用 gsub 或 sub 替换一个字符