从文本字段中的日期中减去天数

Subtract days from a date in a text field

我有一些看起来像这样的文字:

"Word1 word2 word3 word4 12/31/1980 word word words"  
"Word1 word2 word3 11/2/90 word word words 10/2/1991."   
"Word1 8/1/2003 word2 word3 word4 11/8/1990 word word words October 4, 1997 words." 

我想用文本中的日期和另一个日期之间的天数替换当前日期。

例如在这种情况下:

"Word1 word2 word3 word4 1000 word word words"  
"Word1 word2 word3 2000 word word words 2365."  
"Word1 4000 word2 word3 word4 4005 word word words 5000 words." 

(我顺便补了个替换号)

我在使用 mdy() 获取正确的年份时遇到了一些问题。到目前为止,我的解决方案是提取和格式化日期的两步过程,然后在文本字段中检查和替换它。

# extract and format 2 digit year dates

    re <- ".*\s+(\d{1,2}/\d{1,2}/\d{2})\D.*" 
    path$path_date_magic_2year <- mdy(with(path, ifelse(grepl(re,   path_notes),sub(re,'\1',path_notes),'')))

# replace the date in the text with the extracted and formatted date 
    for (i in 1:length(path$path_date_magic_2year)){
      if (!is.na(path$path_date_magic_2year[i])) {
        path$path_date_magic_2year_test[i] <- sub('\d{1,2}/\d{1,2}/\d{2}',              path$path_date_magic_2year[i] , path$path_notes[i])
  }
}

(在我完成 2 位数的年份日期之后,然后我完成 4 位数的年份日期,然后是写出日期的月份。mdy() 理论上可以处理所有这些,但当我这样做时并非所有这些都是正确的最初分开时几乎是完美的。)

就是这样。

当文本字段中只有一个日期时,当前方法有效。

所以我剩下的问题是当文本中有多个日期时如何处理。我在自由文本字段中有 1 到 6 个日期。

我想做的是一步修复所有问题,无论文本字段中的日期数量如何,使用 gsub 进行贪婪替换。不过,我还没有找到一种方法来完成这项工作。

我有什么想法可以让它发挥作用吗?

假设向量 txt 包含您的文本并且 myDate 是被减数:

myDate <- Sys.Date() # for example
Sys.setlocale("LC_TIME", "english") # if needed
regex <- paste0("\d{1,2}/\d{1,2}/\d{2,4}", "|((", paste(month.name, collapse = "|"), ") \d{1,2}, \d{2,4})")
days <- sapply(lapply(matches <- regmatches(txt, gregexpr(regex, txt)), function(x) if (length(x)) as.Date(x, lubridate::guess_formats(x, "mdy"))) , function(date) as.numeric(myDate - date))
for (x in seq_along(txt)) 
  for (y in seq_along(days[[x]])) 
    txt[x] <- sub(matches[[x]][y], days[[x]][y], txt[x], fixed = TRUE)
# [1] "Word1 word2 word3 word4 12518 word word words"                
# [2] "Word1 word2 word3 8925 word word words 8591."                 
# [3] "Word1 4270 word2 word3 word4 8919 word word words 6397 words."