How to check if a string contains a date in Java?

前端 未结 3 816
北海茫月
北海茫月 2021-01-19 05:50

How do I check if a string contains a date of this form:

Sunday, January 15, 2012 at 7:36pm EST

The data I\'m working with contains

3条回答
  •  北荒
    北荒 (楼主)
    2021-01-19 06:34

    You could first check the presence of your date with a regex:

    \w+,\s+\w+\s+\d+\,\s+\d+\s+at\s+\d+:\d+(pm|am)\s+\w{3,4}
    

    This regex matches both

    Rahul Chowdhury Sunday, January 15, 2012 at 7:37pm EST
    Aritra Sinha Nirmal Friday, April 1, 2016 at 10:16pm EDT
    

    https://regex101.com/r/V0dAf8/2/

    When you found the match in your text then you could use SimpleDateFormat to check if it is well formed.

    String input = "Rahul Chowdhury Sunday, January 15, 2012 at 7:37pm EST";
    String regex = "(\\w+,\\s+\\w+\\s+\\d+\\,\\s+\\d+\\s+at\\s+\\d+:\\d+(pm|am)\\s+\\w{3,4})";
    Matcher matcher = Pattern.compile(regex).matcher(input);
    if (matcher.find()) {
      System.out.println(matcher.group(1));
    }
    

    This will print:

    Sunday, January 15, 2012 at 7:37pm EST
    

提交回复
热议问题