使用正则表达式从 R 中的嵌套列表中提取模式

Extracting pattern from the nested list in R using regex

我有以下经过排序的时间段列表 (lst),我想将这些时间段拆分为特定日期,然后在不改变列表顺序的情况下提取最大时间段。

$`1`
[1] "01.12.2015 - 21.12.2015"

$`2`
[1] "22.12.2015 - 05.01.2016"

$`3`
[1] "14.09.2015 - 12.10.2015" "29.09.2015 - 26.10.2015"

因此,调整后的列表应该是这样的:

$`1`
[1] "01.12.2015" "21.12.2015"

$`2`
[1] "22.12.2015"  "05.01.2016" 

$`3`
[1] "14.09.2015"  "12.10.2015" "29.09.2015"  "26.10.2015"

为了做到这一点,我开始拆分列表:

   lst_split <- str_split(lst, pattern = " - ")

这导致以下内容:

[[1]]
[1] "01.12.2015" "21.12.2015"

[[2]]
[1] "22.12.2015" "05.01.2016"

[[3]]
[1] "c(\"14.09.2015"             "12.10.2015\", \"29.09.2015" "26.10.2015\")"  

然后,我尝试提取模式:

lapply(lst_split, function(x) str_extract(pattern = c("\d+\.\d+\.\d+"),x))

但我的输出缺少一个日期 (29.09.2015)

[[1]]
[1] "01.12.2015" "21.12.2015"

[[2]]
[1] "22.12.2015" "05.01.2016"

[[3]]
[1] "14.09.2015" "12.10.2015" "26.10.2015"

有没有人知道我如何让它工作并可能提出更有效的解决方案?提前谢谢你。

1) 使用 strsplit,使用 unlist 展平每个组件,将日期转换为 "Date" class,然后使用 range 获得最大时间跨度。没有使用包。

> lapply(lst, function(x) range(as.Date(unlist(strsplit(x, " - ")), "%d.%m.%Y")))
$`1`
[1] "2015-12-01" "2015-12-21"

$`2`
[1] "2015-12-22" "2016-01-05"

$`3`
[1] "2015-09-14" "2015-10-26"

2) 这种使用 magrittr 管道的变体也有效:

library(magrittr)
lapply(lst, function(x) 
   x %>% 
     strsplit(" - ") %>% 
     unlist %>% 
     as.Date("%d.%m.%Y") %>% 
     range
)

注意: 可重现形式的输入 lst 是:

lst <- structure(list(`1` = "01.12.2015 - 21.12.2015", `2` = "22.12.2015 - 05.01.2016", 
`3` = c("14.09.2015 - 12.10.2015", "29.09.2015 - 26.10.2015"
)), .Names = c("1", "2", "3"))

感谢@WiktorStribiżew 和@akrun 的评论,使用 str_extract_all.

就足够了

在这个例子中:

> str_extract_all(lst,"\d+\.\d+\.\d+")
[[1]]
[1] "01.12.2015" "21.12.2015"

[[2]]
[1] "22.12.2015" "05.01.2016"

[[3]]
[1] "14.09.2015" "12.10.2015" "29.09.2015" "26.10.2015"