我试图使用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'
答案 0 :(得分:4)
答案 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 (...)
。 ?
量词(在+
或*
之后不存在)会将前一个标记变为可选标记。所以(?: (.+))
是可选的。非捕获组内的空间匹配单个空格,(.+)
将剩余的一个或多个字符捕获到另一个组。