2017-09-30 73 views
0

需要幫助,我需要通過此正則表達式傳遞apache日誌文件但不工作,返回false。正則表達式在日誌文件中傳遞Apache每行

private String accessLogRegex() 
{ 
    String regex1 = "^([\\d.]+)"; // Client IP 
    String regex2 = " (\\S+)"; // - 
    String regex3 = " (\\S+)"; // - 
    String regex4 = " \\[([\\w:/]+\\s[+\\-]\\d{4})\\]"; // Date 
    String regex5 = " \"(.+?)\""; // request method and url 
    String regex6 = " (\\d{3})"; // HTTP code 
    String regex7 = " (\\d+|(.+?))"; // Number of bytes 
    String regex8 = " \"([^\"]+|(.+?))\""; // Referer 
    String regex9 = " \"([^\"]+|(.+?))\""; // Agent 

    return regex1+regex2+regex3+regex4+regex5+regex6+regex7+regex8+regex9; 
} 

Pattern accessLogPattern = Pattern.compile(accessLogRegex()); 
Matcher entryMatcher; 
String log = "64.242.88.10 | 2004-07-25.16:36:22 | "GET /twiki/bin/rdiff/Main/ConfigurationVariables HTTP/1.1" 401 1284 | Mozilla/4.6 [en] (X11; U; OpenBSD 2.8 i386; Nav)"; 

entryMatcher = accessLogPattern.matcher(log); 
if(!entryMatcher.matches()){ 
    System.out.println("" + index +" : couldn't be parsed"); 
} 

我已經包含apache日誌的樣本,它的點(「|」)分開。

回答

0

是否有你想使用正則表達式的原因?這些都是很容易出錯,容易出錯,可維護的噩夢......

另一種可能是使用這個庫,例如this one

也就是說,如果你想使用正則表達式,你包含了一些錯誤的:你給示例日誌行

String regex1 = "^([\\d.]+)"; // while quite liberal, this should work 
String regex2 = " (\\S+)"; // matches the first pipe 
String regex3 = " (\\S+)"; // this will match the date field 
String regex4 = " \\[([\\w:/]+\\s[+\\-]\\d{4})\\]"; // date has already been matched so this won't work, also this is all wrong 
String regex5 = " \"(.+?)\""; // you're not matching the pipe character before the URL; also, why the ? 
String regex6 = " (\\d{3})"; // HTTP code 
String regex7 = " (\\d+|(.+?))"; // Why are you also matching any other characters than just digits? 
String regex8 = " \"([^\"]+|(.+?))\""; // Your sample log line doesn't contain a referer 
String regex9 = " \"([^\"]+|(.+?))\""; // Agent is not enclosed in quotes 

一個可能的解決方案正則表達式是此:

String regex1 = "^([\\d.]+)"; // digits and dots: the IP 
String regex2 = " \\|"; // why match any character if you *know* there is a pipe? 
String regex3 = " ((?:\\d+[-:.])+\\d+)"; // match the date; don't capture the inner group as we are only interested in the full date 
String regex4 = " \\|"; // pipe 
String regex5 = " \"(.+)\""; // request method and url 
String regex6 = " (\\d{3})"; // HTTP code 
String regex7 = " (\\d+)"; // Number of bytes 
String regex8 = " \\|"; // pipe again 
String regex9 = " (.+)"; // The rest of the line is the user agent 

當然這可能需要進一步調整,如果其他日誌行不遵循完全相同的格式。

+0

謝謝@ brain99,使用解析器lib,我試圖以這種格式傳遞時間yyyy-MM-dd.HH:mm:ss用於'%{format} t'string。 –

+0

如果使用我鏈接的庫,當然 - 只需配置日誌格式正確(我相信它應該像'String logformat =「%h |%{%Y-%m-%d。%H:%M:%然後,您可以選擇將日期作爲時間戳檢索,或者在您的POJO(年份,月份)中包含單個字段,天,...) – brain99

+0

哇,你是最好的...請能夠上面的logformat工作爲由pip分隔的任何apache日誌文件謝謝 –

相關問題