2017-06-05 94 views
0

我想解析一个正则表达式的日志文件,我明白拉出IP寻址的第一个,但我坚持如何超越其余部分的日志文件。因此,开始分析剩下的东西,我只是在正则表达式上解析出日期等?所以我会第二个元素是72.37.100.86的第二个IP。然后,我想排除“ - - - ”并将日期作为第4个元素以及“GET/HTTP/1.1:”作为第8个索引以及状态代码200作为第9个索引。任何有关这方面的帮助将非常感谢您了解我接下来要做的事情。试图用正则表达式解析日志文件

package com.text.nginx_log_parser; 

import java.util.regex.Matcher; 
import java.util.regex.Pattern; 
public class RegExTester { 


// Actual Entry : 10.10.100.151 - 72.37.100.86, 192.36.20.508 - - - [04/Jul/2016:12:50:06 +0000] https https https "GET/HTTP/1.1" 200 20027 "-" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.107 Safari/537.36" 
public static String logEntry = "10.10.100.151 - 72.37.100.86, 192.36.20.508 - - - [04/Jul/2016:12:50:06 +0000] https https https \"GET/HTTP/1.1\" 200 20027 \"-\" \"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.107 Safari/537.36\"\r\n"; 

//public static String regex = "(\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3})"; 
//public static String regex = "(\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3})"; 
public static void main (String [] args){ 

    String regex = "(\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3})\\s*-*\\s*-*\\s*-*"; 
    regexChecker(regex, logEntry); 
    regex = "\\[*\\]\\s."; 
    regexChecker(regex, logEntry); 
} 

public static void regexChecker(String regex, String str){ 

    Pattern pattern = Pattern.compile(regex); 

    Matcher matcher = pattern.matcher(logEntry); 
    //String firstIP = matcher.group(0); 
    //String secondIP = matcher.group(); 
    //String timestamp = 
    while(matcher.find()){ 
     System.out.println(matcher.group(0)); 
    } 
    } 
} 
+0

什么输出你期望从这个字符串? –

回答

1

用下面的正则表达式:

(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})[-\s]+(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}).+?\[(.+?)\].*?\"(.+?)\"\s(\d{3}).*$ 

你通过看着捕捉组按照this entry on regex101.com