I'm trying to parse an Apache Log with regex using Python and assign it to separate variables.
ACCESS_LOG_PATTERN = '^(\S+) (\S+) (\S+) \[([\w:/]+\s[+\-]\d{4})\] "(\S+) (\S+)\s*(\S+)\s*" (\d{3}) (\S+)'
logLine='127.0.0.1 - - [01/Jul/1995:00:00:01 -0400] "GET /images/launch-logo.gif HTTP/1.0" 200 1839'
I will parse and group it into the following variable:
match = re.search(APACHE_ACCESS_LOG_PATTERN, logLine)
host = match.group(1)
client_identd = match.group(2)
user_id = match.group(3)
date_time = match.group(4)
method = match.group(5)
endpoint = match.group(6)
protocol = match.group(7)
response_code = int(match.group(8))
content_size = match.group(9)
The regex pattern is working fine for the log line, but the parsing/regex match fails for the following case:
'127.0.0.1 - - [01/Jul/1995:00:00:01 -0400] "GET /" 200 1839'
'127.0.0.1 - - [01/Jul/1995:00:00:01 -0400] "GET / " 200 1839'
How do I fix this?
RESULT
You need to make your
group 7
optional by adding a?
. Use the following regex:See the DEMO