gpt4 book ai didi

Python 正则表达式 : How to append string if found and append "Not Found" otherwise?

转载 作者:行者123 更新时间:2023-12-01 03:53:38 27 4
gpt4 key购买 nike

我尝试将结果附加到列表中(如果找到),并将字符串“N/A”附加到列表中(如果未找到匹配项)。 show_version_lists 是来自各种网络设备的日志列表。

import re

for result in show_version_list:

for matchedtext in re.findall(r'(?<=Version).*?(?=-)',result)[:1]:

if re.search(r'(?<=Version).*?(?=-)',result):

version_numbers_xe.append(matchedtext)

else:

version_numbers_xe.append('n/a')

当我运行上面的代码时,else 条件永远不会发生。

应该匹配的日志之一的示例

Load for five secs: 5%/0%; one minute: 4%; five minutes: 4%
Time source is NTP, 15:24:47.756 PDT Thu Jun 16 2016
Cisco IOS XE Software, Version 03.16.01a.S - Extended Support Release
Cisco IOS Software, ASR1000 Software (PPC_LINUX_IOSD-ADVENTERPRISEK9-M), Version 15.5(3)S1a, RELEASE SOFTWARE (fc1)
Technical Support: http://www.cisco.com/techsupport
Copyright (c) 1986-2015 by Cisco Systems, Inc.
Compiled Wed 04-Nov-15 17:40 by mcpre

不应匹配的日志之一的示例。

Cisco IOS Software, C3750E Software (C3750E-UNIVERSALK9-M), Version   15.2(2)E3, RELEASE SOFTWARE (fc3)
Technical Support: http://www.cisco.com/techsupport
Copyright (c) 1986-2015 by Cisco Systems, Inc.
Compiled Wed 26-Aug-15 06:14 by prod_rel_team

编辑:

AChampion 你是对的,去掉 for 循环解决了逻辑问题。

最佳答案

使用re.finditer .

finditer 返回一个匹配对象,我们可以使用 re.group 附加匹配对象中的版本信息。就这么简单。

import re

version_numbers_xe = []

for result in show_version_list:
found = False
for match in re.finditer(r'(?<=Version).*?(?=-)',result):
version_numbers_xe.append(match.group())
found = True
if not found:
version_numbers_xe.append(None)

出于性能原因,我建议预编译您的正则表达式,以生成以下内容:

import re

version_numbers_xe = []
version_regex = re.compile(r'(?<=Version).*?(?=-)')

for result in show_version_list:
found = False
for match in version_regex.finditer(result):
version_numbers_xe.append(match.group())
found = True
if not found:
version_numbers_xe.append(None)

这消除了最后一场比赛的完整性检查,但我不确定为什么你首先要进行它。

关于Python 正则表达式 : How to append string if found and append "Not Found" otherwise?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37870495/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com