【发布时间】: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 的输入