import re
regex = re.compile(r"(?P<remoteAdd>[0-9.]+) - (?P<remoteUser>[a-zA-z]+) \[(?P<timestamp>[^\]]+)] \"(?P<request>[^\"]+)\" (?P<status>[0-9]+) (?P<bodyBytesSent>[0-9]+) \"(?P<httpReferer>[^\"]+)\" \"(?P<httpUserAgent>[^\"]+)\"", flags=re.MULTILINE)
test_str = ("----NGINX----\n\n\n\n"
"127.0.0.1 - dbmanager [20/Nov/2017:18:52:17 +0000] \"GET / HTTP/1.1\" 401 188 \"-\" \"Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:47.0) Gecko/20100101 Firefox/47.0\"\n\n\n\n"
" '$remote_addr - $remote_user [$time_local] \"$request\" '\n"
" '$status $body_bytes_sent \"$http_referer\" '\n"
" '\"$http_user_agent\" \"$http_x_forwarded_for\"'")
matches = regex.finditer(test_str)
for match_num, match in enumerate(matches, start=1):
print(f"Match {match_num} was found at {match.start()}-{match.end()}: {match.group()}")
for group_num, group in enumerate(match.groups(), start=1):
print(f"Group {group_num} found at {match.start(group_num)}-{match.end(group_num)}: {group}")
Please keep in mind that these code samples are automatically generated and are not guaranteed to work. If you find any syntax errors, feel free to submit a bug report. For a full regex reference for Python, please visit: https://docs.python.org/3/library/re.html