python - 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}
解决方案
您使用了具有 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
推荐阅读
- json - Django REST 框架更改 JSON 结构
- .net - 实体图像未显示
- jquery - 在 Bootstrap 中设置弹出框
- linux - QEMU 内存分配问题
- python - 找到顶点之间的路径,在任何两个有食物的节点之间最多有 k 步
- javascript - 当对象在 duktape 中被删除/处置时,我该如何做一些清理工作?
- java - Android Studio Emulators 上是否存在 Android Network Provider?
- r - 如何在两列中查找具有相同值的行?
- r - 包未连接 xlconnect
- python - 使用正则表达式将文本解析为熊猫,但产生了空数据框