Regex 如何通过正则表达式从uri捕获可选参数

Regex 如何通过正则表达式从uri捕获可选参数,regex,python-3.x,logging,nginx,Regex,Python 3.x,Logging,Nginx,以下方法解析nginx日志中的一行: def test_parse_line2(self): groups = ['ip', 'timestamp', 'offset', 'command', 'path', 'protocol', 'status', 'bytes', 'client'] line = '1.2.3.4 - - [22/Oct/2015:12:01:49 -0500] "GET /mypath/?param1=value1&param2=value2 H

以下方法解析nginx日志中的一行:

def test_parse_line2(self):
    groups = ['ip', 'timestamp', 'offset', 'command', 'path', 'protocol', 'status', 'bytes', 'client']
    line = '1.2.3.4 - - [22/Oct/2015:12:01:49 -0500] "GET /mypath/?param1=value1&param2=value2 HTTP/1.1" 200 51 "-" "SomeRandomClient"'
    pattern = r'(?P<ip>[^ ]+) - - \[(?P<timestamp>[^ ]+) (?P<offset>[-\+][0-9]{4})] "' +\
        r'(?P<command>[A-Z]+) /(?P<path>[^ ]+) (?P<protocol>[^"]+)" (?P<status>[0-9]+) (?P<bytes>[0-9]+) (?:[^ ]+)'+\
        r' "(?P<client>[^"]+)'
    match = re.search(pattern, line)
    if match:
        for group_name in groups:
            print(group_name, match.group(group_name))

是否有办法对其进行修改,以便我分别捕获强制路径、mypath和可选参数,param1=value1¶m2=value2?

您需要用两个不同的匹配器替换路径的模式匹配器:?p[^?]+\?p[^]+

在替换后工作?用\??