Is there a shorter way to extract a date from a string?

前端 未结 4 2107
轮回少年
轮回少年 2021-01-12 02:14

I wrote code to extract the date from a given string. Given

  > \"Date: 2012-07-29, 12:59AM PDT\"

it extracts

  > \"         


        
4条回答
  •  暖寄归人
    2021-01-12 02:59

    As (pretty much) always, you've got multiple options here. Though none of them really frees you from getting used to some basic regular expression syntax (or its close friends).

    raw_date <- "Date: 2012-07-29, 12:59AM PDT"
    

    Alternative 1

    > gsub(",", "", unlist(strsplit(raw_date, split=" "))[2])
    [1] "2012-07-29"
    

    Alternative 2

    > temp <- gsub(".*: (?=\\d?)", "", raw_date, perl=TRUE)
    > out <- gsub("(?<=\\d),.*", "", temp, perl=TRUE)
    > out
    [1] "2012-07-29"
    

    Alternative 3

    > require("stringr")
    > str_extract(raw_date, "\\d{4}-\\d{2}-\\d{2}")
    [1] "2012-07-29"
    

提交回复
热议问题