Java 正则表达式日期字符串

标签 java regex

我需要帮助创建一个正则表达式来解析以下字符串:

09-22-11 12:58:40       SEVERE       ...ractBlobAodCommand:104           -   IllegalStateException: version:1316719189017 not found in recent history                             Dump: /data1/aafghani/dev/devamir/logs/dumps/22i125840.dump

对我来说最困难的部分是解析日期。我不是真正的 Java 正则表达式专家 - 感谢您的帮助。

最佳答案

The question is a bit misleading as it implies the need to parse the date into java.util.Date object or similar. The real question is how to split up the input data into the desired fields:

  • date
  • level
  • location name & line
  • exception name & message
  • dump file

这是一种使用正则表达式的解决方案。

String pattern = "^(\\d{2}-\\d{2}-\\d{2} \\d{2}:\\d{2}:\\d{2})" // date
    + "[ ]+(SEVERE|WARNING|INFO|CONFIG|FINE|FINER|FINEST)" // level
    + "[ ]+([^:]+):(\\d+)" // location name, location line
    + "[ ]+-[ ]+([^:]+): (.*?)" // exception name, exception message
    + "[ ]+Dump: ([a-zA-Z0-9\\./]+)" // dump
    + "$";

Pattern regex = Pattern.compile(pattern);
String input = "09-22-11 12:58:40       SEVERE       ...ractBlobAodCommand:104           -   IllegalStateException: version:1316719189017 not found in recent history                             Dump: /data1/aafghani/dev/devamir/logs/dumps/22i125840.dump";
Matcher m = regex.matcher(input);
assertTrue(m.matches());
assertSame(7, m.groupCount());
for (int i = 1; i <= m.groupCount(); i++) {
  System.out.format("[%d] \"%s\"%n", i, m.group(i));
}

输出

[1] "09-22-11 12:58:40"
[2] "SEVERE"
[3] "...ractBlobAodCommand"
[4] "104"
[5] "IllegalStateException"
[6] "version:1316719189017 not found in recent history"
[7] "/data1/aafghani/dev/devamir/logs/dumps/22i125840.dump"

关于Java 正则表达式日期字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7699927/

相关文章:

java - RDF 中使用的 URI 是否需要在 Jena 中取消引用?

Java : Generic method and return type

java - 匿名内部类的访问类型是什么?

Javascript 正则表达式引擎 : Word boundaries not matching at start of string for non-word characters

javascript - 使用或不使用正则表达式在 C# 中查找并替换多个字符串

正则表达式从代码中删除方法

java - 网络应用程序 : safetly update a shared List/Map in the AppContext

java - 如何从 docker 容器访问 gradle 测试报告

使用正则表达式 c 检查 url

java - 如何使用正则表达式来识别JSON字符串中的错误消息?