python - re.findall 在 python 的列表中
问题描述
我有一个如下列表。
sample_text = ['199.72.81.55 -- [01/Jul/1995:00:00:01 -0400] "Get /histpry/appollo/HTTP/1.0" 200 6245',
'unicomp6.unicomp.net -- [01/Jul/1995:00:00:06 -0400] "Get /shuttle/countdown/HTTP/1.0" 200 3985',
'199.120.110.21 -- [01/Jul/1995:00:00:01 -0400] "Get /histpry/appollo/HTTP/1.0" 200 6245',
'burger.letters.com -- [01/Jul/1995:00:00:06 -0400] "Get /shuttle/countdown/HTTP/1.0" 200 3985',
'205.172.11.25 -- [01/Jul/1995:00:00:01 -0400] "Get /histpry/appollo/HTTP/1.0" 200 6245']
我需要在列表中获取所有主机名。预期结果如下。
['199.72.81.55', 'unicomp6.unicomp.net', '199.120.110.21', 'burger.letters.com', '205.172.11.25']
我的代码是:
for i in range(0, len(sample_text)):
s=sample_text[i]
host.append(re.findall('[\d]*[.][\d]*[.][\d]*[.][\d]*|[a-z0-9]*[.][a-z]*[.][a-z]*', s))
print(host)
我的输出:
[['199.72.81.55'], ['unicomp6.unicomp.net'], ['199.120.110.21'], ['burger.letters.com'], ['205.172.11.25']]
我该如何解决?
解决方案
在不使用正则表达式的情况下,您可以直接使用str.split
第一'--'
部分
>>> [i.split('--')[0].strip() for i in sample_text]
['199.72.81.55', 'unicomp6.unicomp.net', '199.120.110.21', 'burger.letters.com', '205.172.11.25']
类似的想法,但使用正则表达式
>>> import re
>>> [re.match(r'(.*) -- .*', i).group(1) for i in sample_text]
['199.72.81.55', 'unicomp6.unicomp.net', '199.120.110.21', 'burger.letters.com', '205.172.11.25']
在这两种情况下,您都可以使用列表推导来替换for
循环
推荐阅读
- kubernetes - docker 官方镜像 hello-world 使用 kubectl 命令不断报告“Back-off restarting failed container”
- python - 如何使用 Raspberry Pi 4 (Python) 对 atMega328p MCU 进行编程
- c# - ASP.Net MVC 如何操作配置文件中的自定义条目
- javascript - 如何获得定义
- amazon-eks - 服务类型=负载均衡器未更新 ELB 实例端口
- typescript - 使用带有 typeScript 的 redux
- keil - 调试器显示在全局变量限制处截断
- python - Django Factory Boy 工厂中的简单计算已关闭
- javascript - 如何提供解决此 Material UI 警告的值?
- html - 我的弹出表单一直闪烁(Windows、Chrome)