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)"

最佳答案

\d+-不匹配,将其替换为与之匹配的东西。例:

Original: "^([\\d.]+) (\\S+) (.+?) \\[([\\w:/]+\\s[+\\-]\\d{4})\\] \"(.+?)\" (\\d{3}) (\\d+) \"([^\"]+)\" \"([^\"]+)\""
Fixed:    "^([\\d.]+) (\\S+) (.+?) \\[([\\w:/]+\\s[+\\-]\\d{4})\\] \"(.+?)\" (\\d{3}) (\\S+) \"([^\"]+)\" \"([^\"]+)\""

关于java - 使用Java中的正则表达式解析字符串行,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/8130383/

10-12 20:28