Python正则表达式适用于动态匹配组对象

时间:2015-02-24 15:05:38

标签: python regex

我试图使用python中的正则表达式从输出中提取几个感兴趣的字段。

假设我的字符串为

Interface1 is down (Administratively down)

我写的正则表达式是:

pat = 'Interface(\d) is (\S)+ (.*)'

并且我能够获得所需的字段,但是当界面启动时,将没有原因打印,我也希望得到该案例的正则表达式..现在正用我写的常规exp,它似乎没有用..有人可以帮忙..

当界面启动时,输出将是

Interface1 is Up
m.group()

Traceback (most recent call last):
  File "<pyshell#38>", line 1, in <module>
    m.group()
AttributeError: 'NoneType' object has no attribute 'group'

2 个答案:

答案 0 :(得分:4)

您需要删除第二个和最后一个捕获组之间的空间才能匹配两者。此外,组外的+运算符使其成为重复组;把它放在里面。

Interface(\d+) is (\S+)(.*)

Regex101

答案 1 :(得分:1)

错误消息是因为当字符串为Interface1 is Up时,你的正则表达式正则表达式在子字符串is之后至少需要两个空格

>>> s1 = "Interface1 is down (Administratively down)"
>>> s2 = "Interface1 is Up"
>>> re.match(r'^Interface(\d) is (\S+)(?: (.+))?$', s1).groups()
('1', 'down', '(Administratively down)')
>>> re.match(r'^Interface(\d) is (\S+)(?: (.+))?$', s2).groups()
('1', 'Up', None)

名为non-capturing group的正则表达式(?:....)captuirng group (...)?量词(在+*之后不存在)会将前一个标记变为可选标记。所以(?: (.+))是可选的。非捕获组内的空间匹配单个空格,(.+)将剩余的一个或多个字符捕获到另一个组。