按顺序执行,而不是全部在一个模式中(如果您有许多这样的行,首先拆分行,也将已编译的模式提取为常量):
String input = "1285957838.880 1 192.168.10.228 TCP_HIT/200 1434 GET http://www.google.com/tools/dlpage/res/c/css/dlpage.css [02/Oct/2010:00:00:38 +0530] je02121 NONE/- text/css";
Matcher matcher = Pattern.compile("\\[.*?\\]|\\S+").matcher(input);
int nr = 0;
while (matcher.find()) {
System.out.println("Match no. " + ++nr + ": '" + matcher.group() + "'");
}
输出:
Match no. 1: '1285957838.880'
Match no. 2: '1'
Match no. 3: '192.168.10.228'
Match no. 4: 'TCP_HIT/200'
Match no. 5: '1434'
Match no. 6: 'GET'
Match no. 7: 'http://www.google.com/tools/dlpage/res/c/css/dlpage.css'
Match no. 8: '[02/Oct/2010:00:00:38 +0530]'
Match no. 9: 'je02121'
Match no. 10: 'NONE/-'
Match no. 11: 'text/css'
正则表达式解释:
\\[ match an opening square brace
.*? and anything up to a
\\] closing square brace
| or
\\S+ any sequence of multiple non-whitespace characters