首页 > 解决方案 > 如何从字符串中捕获日期?

问题描述

我有一个这样的字符串变量,"/etc/opt/eset/esets/license/esets_abd9c6.lic: ESET File Security, 2019-07-29 00:00:00, Mynet"我需要从该字段中捕获日期值,但我无法弄清楚。

String string = "/etc/opt/eset/esets/license/esets_abd9c6.lic: ESET File Security, 2019-07-29 00:00:00, Mynet";
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Pattern p = Pattern.compile("");
Matcher m = p.matcher(input);
Date tempDate = null;
if(m.find())
{
    tempDate = format.parse(m.group());
}
System.out.println("" + tempDate);

是否有任何正则表达式模式用于从字符串变量中捕获日期值?

标签: javaregexdatetime

解决方案


对于日期字符串,您可以使用:

\b\d{4}-\d{2}-\d{2}\b

请参阅regex101.com 上的演示并注意您需要两个反斜杠Java(因此...\\b\\d{4}...


这是

\b     # word boundary
\d{4}- # four digits and a "-"
\d{2}-
\d{2}
\b

推荐阅读