Recognise an arbitrary date string

后端 未结 14 863
抹茶落季
抹茶落季 2020-12-01 16:18

I need to be able to recognise date strings. It doesn\'t matter if I can not distinguish between month and date (e.g. 12/12/10), I just need to classify the string as being

14条回答
  •  爱一瞬间的悲伤
    2020-12-01 16:33

    I did it with a huge regex (self created):

    public static final String DATE_REGEX = "\b([0-9]{1,2} ?([\\-/\\\\] ?[0-9]{1,2} ?| (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) ?)([\\-/\\\\]? ?('?[0-9]{2}|[0-9]{4}))?)\b";
    public static final Pattern DATE_PATTERN = Pattern.compile(DATE_REGEX, Pattern.CASE_INSENSITIVE); // Case insensitive is to match also "mar" and not only "Mar" for March
    
    public static boolean containsDate(String str)
    {
        Matcher matcher = pattern.matcher(str);
        return matcher.matches();
    }
    

    This matches following dates:

    06 Sep 2010
    12-5-2005
    07 Mar 95
    30 DEC '99
    11\9\2001
    

    And not this:

    444/11/11
    bla11/11/11
    11/11/11blah
    

    It also matches dates between symbols like [],(), ,:

    Yesterday (6 nov 2010)
    

    It matches dates without year:

    Yesterday, 6 nov, was a rainy day...
    

    But it matches:

    86-44/1234
    00-00-0000
    11\11/11
    

    And this doesn't look not anymore like a date. But this is something you can solve by checking if the numbers are possible values for a month, day, year.

提交回复
热议问题