首页 > 解决方案 > 正则表达式从字符串中过滤版本

问题描述

我有以下字符串:

字符串 1-

Cisco IOS Software, C3900 Software (C3900-UNIVERSALK9-M), Version 15.4(3)M3, RELEASE SOFTWARE (fc2) ROM: System Bootstrap, Version 15.0(1r)M16, RELEASE SOFTWARE (fc1)

字符串2-

Cisco IOS XE Software, Version 16.05.01b
Cisco IOS Software [Everest], ISR Software (X86_64_LINUX_IOSD-UNIVERSALK9-M), Version 16.5.1b, RELEASE SOFTWARE (fc1)
licensed under the GNU General Public License ("GPL") Version 2.0.  The
software code licensed under GPL Version 2.0 is free software that comes
GPL code under the terms of GPL Version 2.0.  For more details, see the

从我只需要获取的字符串16.05.01b15.4(3)M3运行正则表达式时获取。

我已经尝试过了,r'((?<=Version\s)\d+\.\d+\(\d+...)' 我无法15.4(3)M3获取16.05.01b

r'((?<=Version\s)\d+\.\d+\(\d+...)'

一个正则表达式应该能够从两个字符串中获取版本,但两者都不给我结果。

标签: pythonregex

解决方案


在您的示例中,版本带有前缀Version并包括:

  • 数字
  • 括号
  • 人物

在这里,我将版本建模为以数字开头并以上述项目的组合继续的东西。

这应该有效:

import re
strings = [
    '-M), Version 15.4(3)M3, RELEA',
    'rap, Version 15.0(1r)M16, RELEA',
    ', Version 16.5.1b, RELEASE',
    're, Version 16.05.01b'
]
version_re = re.compile(r'version (\d[\w.()]+)', flags=re.IGNORECASE)
for s in strings:
    v = version_re.search(s).group(1)
    print(v)

输出:

15.4(3)M3
15.0(1r)M16
16.5.1b
16.05.01b

推荐阅读