【问题标题】:How to capture a Date from a String? [duplicate]如何从字符串中捕获日期? [复制]
【发布时间】:2019-05-20 08:48:57
【问题描述】:

我有一个类似"/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);

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

【问题讨论】:

标签: java regex datetime


【解决方案1】:

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

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

参见a demo on regex101.com 并注意Java 中需要两个反斜杠(因此...\\b\\d{4}...


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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-23
    • 1970-01-01
    • 2015-05-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多