python - 从单个长行中提取特定字符串
问题描述
我正在尝试从包含多个 ID 的单个长行中从某些网络接口中提取 ID。我已经尝试使用 split 没有成功。我将不胜感激
这是输入的示例,请记住这是在单行文本上。
"Authentication success on Interface Gi1/0/20 AuditSessionID 0000000XXXXXXXXXX, Authentication success on Interface Gi1/0/24 AuditSessionID 0000000XXXXXXXXXX, Authentication not succeed on Interface Fi1/0/10 AuditSessionID 0000000XXXXXXXXXX"
我期望只输出 Gi1/0/20 Gi1/0/24 Fi1/0/10
解决方案
正则表达式适合此任务:
import re
text = 'Authentication success on Interface Gi1/0/20 AuditSessionID 0000000XXXXXXXXXX, Authentication success on Interface Gi1/0/24 AuditSessionID 0000000XXXXXXXXXX, Authentication not succeed on Interface Fi1/0/10 AuditSessionID 0000000XXXXXXXXXX'
re.findall('Interface (.*?) ', text)
将re.findall()
返回一个包含您想要的内容的列表。
['Gi1/0/20', 'Gi1/0/24', 'Fi1/0/10']
该模式'Interface (.*?) '
通过匹配以单词“Interface”开头的所有内容,然后是一个空格,然后是某物或什么都没有,然后是另一个空格。前面提到的某事或无事由 表示(.*?)
,它捕获(即,它被添加到 的输出re.findall()
)匹配的任何内容.*?
,即任何字符(.
),任意次数(*
),与匹配()所需的次数一样少?
。您可以在https://regex101.com/等网站上使用正则表达式,这将允许您运行 Python 正则表达式并解释它们(比我能做的更好)。
推荐阅读
- typescript - WebStorm typings.d.ts 类型为红色
- python - Adfuller & KPSS 等价 Python vs R
- android - 小米 Miui 上的 Android 12 启动画面
- jenkins - Jenkins Pipeline - 在循环内并行触发作业
- javascript - 如何在 React 中单击时删除项目
- c - 代码覆盖率显示 Visual Studio 2019 未覆盖的一行
- machine-learning - 无需深度学习或机器学习的图像处理
- python - Python 中的 SQL 查询 - 在 SQL 查询中插入来自 Python 的值
- ios - 在 x 方向平移的 HighCharts 不起作用
- python - Power BI 视觉对象在工作区或 powerapp 中不起作用。修复可能是什么?