java - 来自字符串的模式
问题描述
我想从字符串中提取模式,例如:
string x== "1234567 - israel.ekpo@massivelogdata.net cc55ZZ35 1789 Hello Grok";
pattern its should generate is = "%{EMAIL:username} %{USERNAME:password} %{INT:yearOfBirth}"
基本上我想为java应用程序中生成的日志创建模式。知道该怎么做吗?
解决方案
推荐使用grow 库从日志中提取数据。
例子:
public final class GrokStage {
private static final void displayResults(final Map<String, String> results) {
if (results != null) {
for(Map.Entry<String, String> entry : results.entrySet()) {
System.out.println(entry.getKey() + "=" + entry.getValue());
}
}
}
public static void main(String[] args) {
final String rawDataLine1 = "1234567 - israel.ekpo@massivelogdata.net cc55ZZ35 1789 Hello Grok";
final String expression = "%{EMAIL:username} %{USERNAME:password} %{INT:yearOfBirth}";
final GrokDictionary dictionary = new GrokDictionary();
// Load the built-in dictionaries
dictionary.addBuiltInDictionaries();
// Resolve all expressions loaded
dictionary.bind();
// Take a look at how many expressions have been loaded
System.out.println("Dictionary Size: " + dictionary.getDictionarySize());
Grok compiledPattern = dictionary.compileExpression(expression);
displayResults(compiledPattern.extractNamedGroups(rawDataLine1));
}
}
输出:
username=israel.ekpo@massivelogdata.net
password=cc55ZZ35
yearOfBirth=1789
笔记:
这是之前使用的模式:
- 电子邮件
%{\S+}@%{\b\w+\b}\.%{[a-zA-Z]+}
- 用户名
[a-zA-Z0-9._-]+
- INT
(?:[+-]?(?:[0-9]+))
有关 grok 模式的更多信息:BuiltInDictionary.java
推荐阅读
- javascript - Html 按钮不会触发并且不会调用服务器端
- apache - 使用负载均衡器在 domain1.com 和 domain2.com 之间进行 Apache 重定向
- javascript - JS:按两个字段对数组进行排序
- php - php - 从文件夹中获取 xml 文件,循环并获取内容
- javascript - 异步/等待返回承诺
- python - 不同的距离取决于在 python 中使用 fastdtw 的输入顺序
- rust - 在 Rust 2018 中跨模块调用函数时出现“未解析的导入”
- php - BadMethodCallException 调用未定义的方法 App\registeration::register()
- apache-spark - 是否可以在 hadoop3 集群上运行 Spark (2.3) 作业,特别是 HDP 3.1 和 CDH6 (beta)
- react-native - 访问 redux-persist 中的数据(react native)