简体   繁体   English

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

[英]Python regular expression to work for dynamic match group objects

I'm trying to extract few interested fields from an output using Regular expression in python. 我正在尝试使用python中的正则表达式从输出中提取一些感兴趣的字段。

Assuming my string as 假设我的字符串为

Interface1 is down (Administratively down)

The regular expression that i have written is: 我写的正则表达式是:

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

and i was able to get the required fields but when the interface is up, there will not be reason printed and i wanted to get the regex work for that case too.. right now with the regular exp that i have written, it does not seem to work.. can someone pls help.. 并且我能够获得必填字段,但是当界面启动时,就没有理由打印了,我也想让这种情况下的正则表达式工作..现在我用我编写的常规exp了,它没有似乎工作..有人可以帮忙..

When the interface is up, the output would be 当接口打开时,输出将是

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'

You need to remove the space between the second and last capturing group in order to match both. 您需要删除第二个捕获组和最后一个捕获组之间的空间,以使两者匹配。 Also, the + operator outside of the group makes it a repeating group; 同样,组外的+运算符使其成为重复组; place it inside instead. 放在里面。

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

Regex101 Regex101

The error message is because when the string is Interface1 is Up , your regex regex expects atleast two spaces after the substring is 该错误消息是因为当字符串为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)

In regex (?:....) called non-capturing group and (...) called captuirng group . 在正则表达式中, (?:....)称为非捕获组,(...)称为captuirng组 ? quantifier (which is not present just after to + or * ) would turn the previous token as optional one. 量词(紧接在+*之后不存在)会将前一个标记设为可选标记。 So (?: (.+)) is an optional one. 因此(?: (.+))是可选的。 space inside the non-capturing group matches a single space and the (.+) captures all the remaining one or more characters to another group. 非捕获组中的空格与单个空格匹配,并且(.+)将所有剩余的一个或多个字符捕获到另一组中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM