使用正则表达式解析日志

我正在寻找一种解析Varnish日志文件的解决方案。看起来像:

178.232.38.87 - - [23/May/2012:14:01:05 +0200] "GET http://static.vg.no/iphone/js/front-min.js?20120509-1 HTTP/1.1" 200 2013 "http://touch.vg.no/" "Mozilla/5.0 (Linux; U; Android 2.3.3; en-no; HTC Nexus One Build/GRI40) AppleWebKit/533.1 (KHTML, like Gecko) Version/4.0 Mobile Safari/533.1"

可以区分以下元素:

%h %l %u %t "%r" %s %b "%{Referer}i" "%{User-agent}i"

但我仍然不知道该怎么做。简单String.split(" ");行不通。

我知道正则表达式具有一般规则,但最合适的是Java。

谢谢

回答:

我想出了一种根据可能的/期望的值从与各个字段匹配的块中构建正则表达式的方法。

    String rexa = "(\\d+(?:\\.\\d+){3})";  // an IP address

String rexs = "(\\S+)"; // a single token (no spaces)

String rexdt = "\\[([^\\]]+)\\]"; // something between [ and ]

String rexstr = "\"([^\"]*?)\""; // a quoted string

String rexi = "(\\d+)"; // unsigned integer

String rex = String.join( " ", rexa, rexs, rexs, rexdt, rexstr,

rexi, rexi, rexstr, rexstr );

Pattern pat = Pattern.compile( rex );

Matcher mat = pat.matcher( h );

if( mat.matches() ){

for( int ig = 1; ig <= mat.groupCount(); ig++ ){

System.out.println( mat.group( ig ) );

}

}

当然,可以用rex代替rexa或rexi。

以上是 使用正则表达式解析日志 的全部内容, 来源链接: utcz.com/qa/423287.html

回到顶部