【问题标题】:Extract dates from a vector of character strings从字符串向量中提取日期
【发布时间】:2016-08-27 22:16:09
【问题描述】:

我有两个元素的向量。每个元素都包含一个字符串 有两组日期。我需要提取这两个日期中的后者, 并用它们创建一个新的向量或列表。

#webextract vector
webextract <- list("The Employment Situation, December 2006       January  5  \t 8:30 am\r","The Employment Situation, January 2007        \tFeb.  2, 2007\t 8:30 am            \r") 

#This is how the output of webextract looks like:
[[1]]
[1] The Employment Situation, December 2006       January  5  \t 8:30 am\r

[[2]]
[1] The Employment Situation, January 2007        \tFeb.  2, 2007\t 8:30 am            \r

webextract 是网络抓取纯文本 URL 的结果,这就是它看起来像这样的原因。我需要提取的是“1 月 5 日”和“2 月 2 日”。我一直在尝试grepstrsplit,但没有成功。已经完成了所有相关的 SO 问题,但没有成功。感谢您的帮助。

【问题讨论】:

  • gsub('.+\\s{3}(.+\\d+?).*', '\\1', unlist(webextract))stringr::str_extract(unlist(webextract), '(?&lt;=\\s{4})\\w.+?\\d+'),也许

标签: r string parsing vector extraction


【解决方案1】:

我们可以在unlisting 'webextract' 之后尝试使用gsub

gsub("^\\D+\\d+\\s+|(,\\s+\\d+)*\\D+\\d+:.*$", "", unlist(webextract))
#[1] "January  5" "Feb.  2"   

【讨论】:

  • 谢谢阿克伦。 "^\\D+\\d+\\s+|(,\\s+\\d+)*\\D+\\d+:.*$" 代表模式,对吗?
  • @Gracos 是的,它表示要从字符串中匹配和删除的模式。即一个或多个非数字 (\\D+) 后跟数字 (\\d+) 后跟空格 (\\s+) 删除“就业情况,2006 年 12 月”或 |,如果后面有字符 ,在某些字符串中,空格后跟数字,我们使用零个或多个 (*),后跟非数字 (\\D+),数字 (\\d+),后跟 :,其余字符直到结尾(.*$)。 :8:30 中的: 匹配
  • 你是如何在二月之前摆脱“\t”的?这是我唯一不明白的部分。非常感谢!
  • @Gracos \\s+ 将匹配这些字符。
  • 匹配\r, \n, \t等。例如gsub("\\s+", "", "\t Sept \n") [1] "Sept"
猜你喜欢
  • 1970-01-01
  • 2011-02-17
  • 2020-08-14
  • 2016-06-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多