2011-04-20 65 views
0

對於給定的輸入例如:解析碼頭日誌記錄

70.80.110.200 - - [12/Apr/2011:05:47:34 +0000] "GET /notify/click?r=http://www.xxxxxx.com/hello_world&rt=1302587231462&iid=00000 HTTP/1.1" 302 0 "-" "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0; Trident/4.0; FunWebProducts; HotbarSearchToolbar 1.1; SLCC1; .NET CLR 2.0.50727; Media Center PC 5.0; .NET CLR 3.5.30729; .NET CLR 3.0.30729; .NET4.0C; AskTbFWV5/5.11.3.15590)" 4 4 

我想定義以下解析邏輯(可能正則表達式)

  1. 提取IP(3位數字,圓點)* 4 => 70.80.110.200
  2. 提取物的時間=> 12 /月/ 2011
  3. 提取時間=> 5點47分34秒
  4. 提取URI(以\開頭,以\「結尾)。 => /notify/click?r=http://www.xxxxxx.com/hello_world & RT = 1302587231462 & IID = 00000

回答

1

完整代碼示例(基於hsz's answer):

import java.util.*; 
import java.util.regex.*; 

public class RegexDemo { 

    public static void main(String[] argv) { 
    String pat = "^([0-9.]*).*?\\[(\\d+\\/\\w+\\/\\d+):(\\d+:\\d+:\\d+).*?\\].*?(\\/[^ ]*).*$"; 
    Pattern p = Pattern.compile(pat); 
    String target = "70.80.110.200 - - [12/Apr/2011:05:47:34 +0000] \"GET /notify/click?r=http://www.xxxxxx.com/hello_world&rt=1302587231462&iid=00000 HTTP/1.1\" 302 0 \"-\" \"Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0; Trident/4.0; FunWebProducts; HotbarSearchToolbar 1.1; SLCC1; .NET CLR 2.0.50727; Media Center PC 5.0; .NET CLR 3.5.30729; .NET CLR 3.0.30729; .NET4.0C; AskTbFWV5/5.11.3.15590)\" 4 4"; 
    Matcher m = p.matcher(target); 
    System.out.println("pattern: " + pat); 
    System.out.println("target: " + target); 

    if (m.matches()) { 
     System.out.println("found"); 
     for (int i=0; i <= m.groupCount(); ++i) { 
     System.out.println(m.group(i)); 
     } 
    } 
    } 
} 
2

確保碼頭被配置爲執行NSCA兼容日誌記錄,則可以使用任何NCSA日誌分析器來分析日誌。

如果你想手工完成,那麼這是一個很好的正則表達式用例。

3

與嘗試:

/^([0-9.]+).*?\[(\d+\/\w+\/\d+):(\d+:\d+:\d+).*?\].*?(\/[^ ]*).*$/ 

如您所願,在以下組(1,2,3,4)你會得到你所指定的所有數據 - 例如.group(3)是時間。

+0

能否請您提供這樣的代碼示例? – 2011-04-20 11:40:48

+0

對不起,但沒有 - 使用谷歌/書來找到如何在Java中使用正則表達式。 – hsz 2011-04-20 11:41:54

+0

不是100%正確的 - 固定版本:r = /^([0-9.]*).*?\[(\d+\/\w+\/\d+):((dd::d+:\d+) (原始版本只匹配一個數字/句號而不是整個組,並且它不會偏離方括號) – 2011-04-20 11:50:37

0

你可以嘗試以下方法:

String s = "70.80.110.200 - - [12/Apr/2011:05:47:34 +0000] \"GET /notify/click?r=http://www.xxxxxx.com/hello_world&rt=1302587231462&iid=00000 HTTP/1.1\" 302 0 \"-\" \"Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0; Trident/4.0; FunWebProducts; HotbarSearchToolbar 1.1; SLCC1; .NET CLR 2.0.50727; Media Center PC 5.0; .NET CLR 3.5.30729; .NET CLR 3.0.30729; .NET4.0C; AskTbFWV5/5.11.3.15590)\" 4 4"; 
Pattern p = Pattern.compile("^(\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}).*?\\" + //ip 
          "[([^:]*):"+ //date 
          "(\\d{2}:\\d{2}:\\d{2}).*?\\].*?"+ //time 
          "(/[^\\s]*).*$"); //uri 

Matcher m = p.matcher(s); 
if(m.find()){ 
    String ip = m.group(1); 
    String date = m.group(2); 
    String time = m.group(3); 
    String uri = m.group(4); 
}