如何检查字符串是否包含Java中的日期? [英] How to check if a string contains a date in Java?

查看:1163
本文介绍了如何检查字符串是否包含Java中的日期?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何检查字符串是否包含此表格的日期:

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


2012年1月15日星期日美国东部时间下午7:36

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

我正在使用的数据包含大量字符串。但我正在寻找的字符串类型包含2或3个字的名称和日期。我正在检查日期以识别这些类型的字符串。

The data I'm working with contains a ton of strings. But the type of string I'm looking for contains a 2 or 3 word name and a date. I'm checking for dates to identify these types of strings.

我已经找到了这种类型日期的simpleDateFormat。

I've figured out the simpleDateFormat for this type of date.

String string1 = "Rahul Chowdhury Sunday, January 15, 2012 at 7:37pm EST";
String string2 = "Aritra Sinha Nirmal Friday, April 1, 2016 at 10:16pm EDT";    

SimpleDateFormat format = new SimpleDateFormat("EEEEE, MMM dd, yyyy 'at' hh:mmaa z");

但我不知道如何继续前进。

But I have no idea how to proceed further.

我猜测正则表达式可能有效,但我不知道如何在月/日名称的长度变化时实现。即'May'比'December'短得多。

I'm guessing regex might work but I don't know how to implement that when the length of the names of months/days vary. i.e. 'May' is much shorter than 'December'.

我想知道是否有使用正则表达式的解决方案或更简单的解决方案。

我知道有其他线程提出类似的问题,但他们没有回答我的问题。

推荐答案

您可以先用正则表达式检查日期是否存在:

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}

这个正则表达式匹配

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 /

当您在文本中找到匹配项时,您可以使用 SimpleDateFormat 检查它是否形成良好。

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));
}

这将打印:

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

这篇关于如何检查字符串是否包含Java中的日期?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆