extracdate extraction from string

How do I extract the date itself from an expression using regular expressions?
I applied the code below but there seems to be a more elegant solution

i <- "1day-2021-3-2--20-0.csv"
ii = as.POSIXct(sub("--20-0.csv", "", sub("1day-", "", i)))

Something like this?

i <- c("1day-2021-3-2--20-0.csv", "2day-2021-3-3--20-0.csv", "31day-2021-3-31--20-0.csv")

pattern <- "([0-9]{4}-[0-9]{1,2}-[0-9]{1,2})"
m <- regexpr(pattern, i)
as.POSIXct(regmatches(i, m))
#> [1] "2021-03-02 CET"  "2021-03-03 CET"  "2021-03-31 CEST"

Created on 2021-03-03 by the reprex package (v1.0.0)

Many thanks for your help!

1 Like

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.