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

标签 python regex

我尝试将结果附加到列表中(如果找到),并将字符串“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/

相关文章:

php - 如何在 PHP 中将大写单词字符与正则表达式匹配?

python - 用于匹配 IPv4 地址的正则表达式

python - 用两个固定长度的数字对正则表达式进行分组并删除其前导零

python - 如何将某些特定的 .jpg 文件复制到另一个目录?

python - 使用 boto,在 s3 上已经存在的文件上设置 content_type

python - 根据文档,Django 1.8 inspectdb 命令看不到 PostgreSQL View

java - 如何使用 Java Pattern 和 Matcher 在字符串中查找 2 次字符串?

python - 自动从列表中加入 pandas 数据框

python __getattr__ 自动完成

html - 自动化 CSS 图像内联的工具