首页 > 解决方案 > python中带有组名的正则表达式

问题描述

我开始玩python3.8 re lib,发现奇怪的东西。首先,我在网上制作我的正则表达式来测试它是如何工作的,当我发现它已经在工作时,我在 python 中尝试。

test_string = [Tues Jan 20 11:35:13.405644 2020] [access_compat:error] [pid 1871:tid 140301098780416] [client 192.168.123.9:59662] AH01797: client denied by server configuration: /var/www/website/401.html

res = re.compile(r"(?P<Time>\w+\s\w+\s\d+\s\d+:\d+:\d{2})|(?P<Type>[a-zA-Z]+_\w+:\w+)", re.VERBOSE)

for line in logfile:
    line = res.search(line)
    print(line.groupdict())

我正在尝试像那样解析日志行。但我得到以下结果:

类型:无

我不知道为什么或如何解决它,有什么想法吗?:

{'time': Mon Jan 20 11:34:13, 'type': access_compat:error}

标签: pythonregexpython-3.x

解决方案


您使用了具有 2 个备选方案的模式,而您应该使用同时匹配两个备选方案的模式,例如:

(?P<Time>\w+\s\w+\s\d+\s\d+:\d+:\d{2}).+?(?P<Type>[a-zA-Z]+_\w+:\w+)

或者

'time': (?P<Time>\w+\s\w+\s\d+\s\d+:\d+:\d{2}), 'type': (?P<Type>[a-zA-Z]+_\w+:\w+)

有关工作示例,请参见https://regex101.com/r/v6g791/1


推荐阅读