使用Java中的正则表达式解析String Line

时间:2011-11-15 01:19:10

标签: java regex

public static String entryPattern = "^([\\d.]+) (\\S+) (.+?) \\[([\\w:/]+\\s[+\\-]\\d{4})\\] \"(.+?)\" (\\d{3}) (\\d+) \"([^\"]+)\" \"([^\"]+)\"";

    public static void parseTwigLine(String line) {
        Pattern p = Pattern.compile(entryPattern);
        Pattern p1;
        Matcher matcher = p.matcher(line);
        System.out.println(matcher.groupCount());
        if (!matcher.matches() || NUM_FIELDS != matcher.groupCount()) {
          System.err.println("Bad log entry (or problem with RE?):");
          System.err.println(line);
          return;
        }

        timeStamp = matcher.group(4);
        ipAddress = matcher.group(1);
        if (!matcher.group(3).equals("-")) {
        userName = matcher.group(3);
        }
        request = matcher.group(5);
        response = matcher.group(6);
        bytesSent = matcher.group(7);
        browser = matcher.group(9);

        if (!matcher.group(8).equals("-"))
         url = matcher.group(8);
        instanceName = url.split("/")[3];
        if(request.contains("?q")) {
            queryTerms = request.split("[?|&]")[1];
        } else if(url.contains("?q")) {
            queryTerms = url.split("[?|&]")[1].split("=")[1];
        }
        if(request.contains("&f")) {
            filters = request.split("&f=")[1];
        } else if(url.contains("&f")) {
            filters = request.split("&f=")[1];
        }

    }

对于下面这行,我的正则表达式没有得到匹配..任何建议为什么会发生。因为我总是从上面的代码中得到Bad log entry (or problem with RE?)的错误。我的正则表达式有什么问题

10.53.32.1 - - [14/Nov/2011:09:45:56 -0800] "GET /host-ui/themes/client/images/preview/left6_na.gif HTTP/1.1" 304 - "http://search.host.com/search-ui/?q=8960" "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.1; WOW64; Trident/5.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C; .NET4.0E; MS-RTC LM 8; InfoPath.3; BOIE9;ENUS)"

对于下面这行,它正在匹配 -

10.53.32.1 - - [14/Nov/2011:09:45:56 -0800] "GET /host-ui/themes/client/images/btn_close_include.png HTTP/1.1" 200 1023 "http://search.host.com/search-ui/?q=8960" "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.1; WOW64; Trident/5.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C; .NET4.0E; MS-RTC LM 8; InfoPath.3; BOIE9;ENUS)"

1 个答案:

答案 0 :(得分:1)

\d+-不匹配,请将其替换为Original: "^([\\d.]+) (\\S+) (.+?) \\[([\\w:/]+\\s[+\\-]\\d{4})\\] \"(.+?)\" (\\d{3}) (\\d+) \"([^\"]+)\" \"([^\"]+)\"" Fixed: "^([\\d.]+) (\\S+) (.+?) \\[([\\w:/]+\\s[+\\-]\\d{4})\\] \"(.+?)\" (\\d{3}) (\\S+) \"([^\"]+)\" \"([^\"]+)\"" 。例如:

{{1}}