首页 > 解决方案 > 从单个长行中提取特定字符串

问题描述

我正在尝试从包含多个 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

标签: pythontext-parsing

解决方案


正则表达式适合此任务:

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 正则表达式并解释它们(比我能做的更好)。


推荐阅读