如何在不编写正则表达式的情况下解析字符串中的日期?

bir*_*ird 1 r date readr

readr包中有一个名为的函数parse_number,它返回 a 中的数字string

readr::parse_number("Hello 2022!")

[1] 2022
Run Code Online (Sandbox Code Playgroud)

是否有类似的方法从 a 返回日期string?有readr一个名为的函数parse_date,但它做了一些不同的事情:

readr::parse_date("X2018-01-11_poland")

Warning: 1 parsing failure.
row col   expected             actual
  1  -- date like  X2018-01-11_poland

[1] NA
Run Code Online (Sandbox Code Playgroud)

期望的输出:

# the raw string is "X2018-01-11_poland"
2018-01-11
Run Code Online (Sandbox Code Playgroud)

PS 我对使用正则表达式执行此操作不感兴趣。

awc*_*olm 5

包装lubridate内有parse_date_time2易于使用的内容。

library(lubridate)
dstring <- "X2018-01-11_poland"
date <- parse_date_time2(dstring, orders='Ymd')
date
#[1] "2018-01-11 UTC"
Run Code Online (Sandbox Code Playgroud)