2013-10-24 23 views

回答

4

看看這個Java庫

https://github.com/aicer/grok

您可以將其包含在您的項目依靠maven

<dependency> 
    <groupId>org.aicer.grok</groupId> 
    <artifactId>grok</artifactId> 
    <version>0.9.0</version> 
</dependency> 

它帶有預 - 定義的模式,你也可以添加你的。

提取命名模式,結果在映射中可用,組名稱作爲關鍵字,並將檢索到的值映射到這些關鍵字。

final GrokDictionary dictionary = new GrokDictionary(); 

// Load the built-in dictionaries 
dictionary.addBuiltInDictionaries(); 

// Add custom pattern 
dictionary.addDictionary(new File(patternDirectoryOrFilePath)); 

// Resolve all expressions loaded 
dictionary.bind(); 

接下來的這個例子,直接增加了串模式到字典中沒有使用文件

final GrokDictionary dictionary = new GrokDictionary(); 

// Load the built-in dictionaries 
dictionary.addBuiltInDictionaries(); 

// Add custom pattern directly 

dictionary.addDictionary(new StringReader("DOMAINTLD [a-zA-Z]+")); 
dictionary.addDictionary(new StringReader("EMAIL %{NOTSPACE}@%{WORD}\.%{DOMAINTLD}")); 

// Resolve all expressions loaded 
dictionary.bind(); 

下面是如何使用圖書館

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 - [email protected] cc55ZZ35 1789 Hello Grok"; 
    final String rawDataLine2 = "98AA541 - [email protected] mmddgg22 8800 Hello Grok"; 
    final String rawDataLine3 = "55BB778 - [email protected] secret123 4439 Valid Data Stream"; 

    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)); 
    displayResults(compiledPattern.extractNamedGroups(rawDataLine2)); 
    displayResults(compiledPattern.extractNamedGroups(rawDataLine3)); 
    } 
} 
一個完整的例子
相關問題