【问题标题】:scala apache access log regex not workingscala apache访问日志正则表达式不起作用
【发布时间】:2019-09-21 14:58:14
【问题描述】:

我已经为 apache 访问日志定义了正则表达式如下:

val apacheLogPattern = """ ^(\S+) (\S+) (\S+) \[([\w:/]+\s[+\-]\d{4})\] "(\S+)\s?(\S+)?\s?(\S+)?" (\d{3}|-) (\d+|-)\s?"?([^"]*)"?\s?"?([^"]*)?"?$ """.r

还有一个解析日志的函数:

def parse_log(line: String) = {
    line match {
       case apacheLogPattern(ipAddress, clientIdentity, userId, dateTime, method, endPoint, 
        protocol, responseCode, contentSize, browser, somethingElse) => "match"
    }
}

val p = """66.249.69.97 - - [24/Sep/2014:22:25:44 +0000] "GET /071300/242153 HTTP/1.1" 404 514 "-" "Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)"""

parse_log(p)

调用 parse 函数给出 MatchError

scala.MatchError: 66.249.69.97 - - [24/Sep/2014:22:25:44 +0000]“GET /071300/242153 HTTP/1.1”404 514“-”“Mozilla/5.0(兼容;Googlebot/2.​​1;+http://www.google.com/bot.html )" (类 java.lang.String 的) 在 .parse_log(:13) ... 28 省略

有人可以帮我解决 scala 正则表达式的问题吗?

【问题讨论】:

  • 您必须添加 .r,并且您在正则表达式中有 11 个组,但模式匹配只有 10 个。请参阅 ideone.com/lRqyQp 您需要所有这些捕获组吗?
  • 感谢@Thefourthbird 提供代码。它现在工作
  • 感谢@Emma 的输入

标签: regex scala matching


【解决方案1】:

从The fourth bird's comment 开始,正则表达式末尾缺少.r,并且捕获组过多。正确的模式如下所示。

val apacheLogPattern = """^(\S+) (\S+) (\S+) \[([\w:/]+\s[+\-]\d{4})\] "(\S+)\s?(\S+)?\s?(\S+)?" (\d{3}|-) (\d+|-)\s?"?([^"]*)"?\s?"?([^"]*)?"?$""".r

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-06-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-14
    • 1970-01-01
    相关资源
    最近更新 更多