python - 如何使用正则表达式解析 PCI 地址?
问题描述
我正在尝试找到一种可靠的正则表达式模式,用于从sysfs
.
例如:
s = "
# total 0
# drwxr-xr-x 7 root root 0 Mar 22 21:30 .
# drwxr-xr-x 121 root root 0 Mar 22 21:27 ..
# drwxr-xr-x 2 root root 0 Mar 22 21:27 0000:13:45.6:pcie001
# drwxr-xr-x 2 root root 0 Mar 22 21:30 0000:12:34.5
# drwxr-xr-x 2 root root 0 Mar 22 21:30 0000:12:34.6
# -r--r--r-- 1 root root 4096 Mar 22 21:29 aer_dev_correctable
"
pattern = r'SOME MAGIC'
list_of_addrs = re.findall(pattern, s, re.MULTILINE)
我期望的地方list_of_addrs = ['0000:13:45.6:pcie001', '0000:12:34.5', '0000:12:34.6']
我大致尝试编码为正则表达式的模式是:
# Starts with a set of 4 hex characters, [0-9a-fA-F]
# :
# Set of 2 hex characters
# :
# Set of 2 hex characters
# Set of 1 hex characters
# Until next whitespace
解决方案
尝试模式r'\b(0{0,4}:\d{2}:\d{2}.\d:?\w*)'
前任:
import re
s = """
# total 0
# drwxr-xr-x 7 root root 0 Mar 22 21:30 .
# drwxr-xr-x 121 root root 0 Mar 22 21:27 ..
# drwxr-xr-x 2 root root 0 Mar 22 21:27 0000:13:45.6:pcie001
# drwxr-xr-x 2 root root 0 Mar 22 21:30 0000:12:34.5
# drwxr-xr-x 2 root root 0 Mar 22 21:30 0000:12:34.6
# -r--r--r-- 1 root root 4096 Mar 22 21:29 aer_dev_correctable
"""
pattern = r'\b(0{0,4}:\d{2}:\d{2}.\d:?\w*)'
list_of_addrs = re.findall(pattern, s, re.MULTILINE)
print(list_of_addrs)
输出:
['0000:13:45.6:pcie001', '0000:12:34.5', '0000:12:34.6']
推荐阅读
- google-sheets - 按工作日更改行颜色
- python - 简单的请求堆积在队列中
- swift - Marvel API 409 响应,“您必须提供用户密钥”
- nginx - Kubernetes 上的 NGINX 负载均衡
- ubuntu - vim 寄存器是否依赖于 wm 行为?
- php - 带有 PHP Laravel 5.6 的 Quickbooks 桌面应用程序
- ansible - ansible with_items stdout_lines 过滤器
- h2o - 使用 H2O 流量 XGboost 模型
- reactjs - React Apollo GraphQL 搜索/过滤器
- python - 在 python 中更新到现有配置文件部分的特定变量