【问题标题】:Java regex to match datesJava 正则表达式匹配日期
【发布时间】:2014-08-02 10:32:06
【问题描述】:

我正在编写一些用于从非常大的数据集中解析日期的代码。我有以下正则表达式来匹配不同的日期变化

"(((0?[1-9]|1[012])(/|-)(0?[1-9]|[12][0-9]|3[01])(/|-))|"
 +"((january|february|march|april|may|june|july|august|september|october|november|december)"
 + "\\s*(0?[1-9]|[12][0-9]|3[01])(th|rd|nd|st)?,*\\s*))((19|20)\\d\\d)"

匹配格式为“月 dd、yyyy”、“mm/dd/yyyy”和“mm-dd-yyyy”的日期。这适用于这些格式,但我现在遇到欧洲“dd Month,yyyy”格式的日期。我尝试添加 (\\d{1,2})?在正则表达式的开头并添加一个?正则表达式的当前日期匹配部分之后的量词

"((\\d{1,2})?((0?[1-9]|1[012])(/|-)(0?[1-9]|[12][0-9]|3[01])(/|-))|"
 +"((january|february|march|april|may|june|july|august|september|october|november|december)"
 + "\\s*(0?[1-9]|[12][0-9]|3[01])?(th|rd|nd|st)?,*\\s*))((19|20)\\d\\d)"

但这并不完全可行,因为它有时会捕获月份前后的数字字符(例如,'00 January 15, 2013'),有时两者都不会('January 2013')。有没有办法确保捕获两者中的一个?

【问题讨论】:

  • 看看SimpleDateFormat
  • 实际上,SimpleDateFormat 可能不够严格。我会改用 Joda DateTimeFormatter。
  • 如果您知道约会地点,请明确使用SimpleDateFormats。在一个丑陋、可怕、无法维护的正则表达式中正确处理这一点会浪费你宝贵的生命。如果您认真认为它一定是正则表达式,请告诉我们为什么要找到出路。
  • 只有我一个人,还是这个问题每天出现一次?

标签: java regex


【解决方案1】:

为您提供一个满足您要求的 Java 实现(从输入文本中搜索日期):

        String input = "which matches dates of format 'january 31, 1976', '9/18/2013', "
                + "and '11-20-1988'. This works fine for those formats, but I'm now encountering dates" +
                "in the European '26th May, 2020' format. I tried adding (\\d{1,2})? at the"+
                "beginning of the regex and adding a ? quantifier after the current day matching section of the regex as such";

    String months_t = "(january|february|march|april|may|june|july|august|september|october|november|december)";
    String months_d = "(1[012]|0?[1-9])";
    String days_d = "(3[01]|[12][0-9]|0?[1-9])"; //"\\d{1,2}";
    String year_d = "((19|20)\\d\\d)";
    String days_d_a = "(" + days_d + "(th|rd|nd|st)?)";

    // 'mm/dd/yyyy', and 'mm-dd-yyyy'
    String regexp1 = "(" + months_d + "[/-]" + days_d + "[/-]"
            + year_d + ")";
    // 'Month dd, yyyy', and 'dd Month, yyyy'
    String regexp2 = "(((" + months_t + "\\s*" + days_d_a + ")|("
            + days_d_a + "\\s*" + months_t + "))[,\\s]+" + year_d + ")";
    String regexp = "(?i)" + regexp1 + "|" + regexp2;

    Pattern pMod = Pattern.compile(regexp);
    Matcher mMod = pMod.matcher(input);

    while (mMod.find()) {
        System.out.println(mMod.group(0));
    }

输出是:

january 31, 1976
9/18/2013
11-20-1988
26th May, 2020

【讨论】:

    猜你喜欢
    • 2011-08-24
    • 2011-06-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-09-08
    • 2011-12-17
    • 1970-01-01
    相关资源
    最近更新 更多