鉴于您不知道数据的内容,您的工作是探索性的,这意味着您的第一步是询问数据。尽可能多地寻找日期格式。你会摆脱最常见的。我从用 R 编写的方法开始。你可以用你选择的语言做类似的事情。
您永远不会知道有多少日期是您没有想到的格式。但是,您可以尝试一些开放式搜索,这些搜索可能会消除其中的一些,甚至匹配您希望查看但不符合任何格式的有缺陷的数据。我包含了一个搜索,它只在搜索字符串中的任意位置查找月份缩写。
为了制作这个演示,我必须在每次添加新的 RegEx 进行测试时剪切并粘贴到测试用例中。编写测试台将是一个令人满意的策略。这可以是一个表格或向量,用于保存您要执行的每个 RegEx 模式,然后是一个简单的循环来迭代运行它们。
这是我的 R 代码。
library(stringr)
# Exploratory date patterns.
# 04/04/2020
fmt1 <- "\\d{2}/\\d{2}/\\d{4}"
# 4/4/2020
fmt2 <- "\\d{1,2}/\\d{1,2}/\\d{4}"
# Apr. 1, 2020
# If I have a large list, I like building it like this so the part I maintain
# is human readable. You can implement this kind of approach in whatever
# language you use.
month_3ltr <- c("Jan", "Feb", "Mar", "Apr", "May")
month_pat <- paste(month_3ltr, "\\.", sep = "")
month_pat <- paste(month_pat, collapse = "|")
fmt3 <- str_c("^(", month_pat, ")\\s\\d{1,2},\\s\\d{4}")
# Review pattern
fmt3
fmt4 <- str_c(month_pat) # Find anything that just mentions a month.
# Keep going, as many formats as you can think of.
# Test data
str1 <- "04/01/2020"
str2 <- "4/1/2020"
str3 <- "Apr. 1, 2020"
str4 <- "Defective data: Apr. First, 2020"
str5 <- "Fake news"
# Test cases
# Format 1
str_extract(str1, fmt1)
str_extract(str2, fmt1)
str_extract(str3, fmt1)
str_extract(str4, fmt1)
str_extract(str5, fmt1)
# Format 2
str_extract(str1, fmt2)
str_extract(str2, fmt2)
str_extract(str3, fmt2)
str_extract(str4, fmt2)
str_extract(str5, fmt2)
# Format 3
str_extract(str1, fmt3)
str_extract(str2, fmt3)
str_extract(str3, fmt3)
str_extract(str4, fmt3)
str_extract(str5, fmt3)
# Format 4
str_extract(str1, fmt4)
str_extract(str2, fmt4)
str_extract(str3, fmt4)
str_extract(str4, fmt4)
str_extract(str5, fmt4)
我的结果:
> # Test cases
> # Format 1
> str_extract(str1, fmt1)
[1] "04/01/2020"
> str_extract(str2, fmt1)
[1] NA
> str_extract(str3, fmt1)
[1] NA
> str_extract(str4, fmt1)
[1] NA
> str_extract(str5, fmt1)
[1] NA
>
> # Format 2
> str_extract(str1, fmt2)
[1] "04/01/2020"
> str_extract(str2, fmt2)
[1] "4/1/2020"
> str_extract(str3, fmt2)
[1] NA
> str_extract(str4, fmt2)
[1] NA
> str_extract(str5, fmt2)
[1] NA
>
> # Format 3
> str_extract(str1, fmt3)
[1] NA
> str_extract(str2, fmt3)
[1] NA
> str_extract(str3, fmt3)
[1] "Apr. 1, 2020"
> str_extract(str4, fmt3)
[1] NA
> str_extract(str5, fmt3)
[1] NA
>
> # Format 4
> str_extract(str1, fmt4)
[1] NA
> str_extract(str2, fmt4)
[1] NA
> str_extract(str3, fmt4)
[1] "Apr."
> str_extract(str4, fmt4)
[1] "Apr."
> str_extract(str5, fmt4)
[1] NA