[英]Matching pattern over multiple lines in Python
I am new to Python regex. 我是Python正则表达式的新手。 I trying to get below lst from the output.
我试图从输出低于lst。
output="""
IP = 10.10.10.1
BGP version 4, remote router ID 0.0.0.0
State = Established
IP = 10.10.10.2
BGP version 4, remote router ID 0.0.0.0
State = Active
IP = 10.10.10.3
BGP version 4, remote router ID 0.0.0.0
State = Active
IP = 10.10.10.4
BGP version 4, remote router ID 0.0.0.0
State = Established
"""
I am trying with below regex but no luck. 我正在尝试以下正则表达式,但没有运气。 Can someone please help me.
有人可以帮帮我吗。
lst = re.findall(r'IP = (\S+)\n\nState = (\S+)',output, re.M)
lst
should be filled with lst
应该充满
[('10.10.10.1', 'Established'), ('10.10.10.2', 'Active'), ('10.10.10.3', 'Active'), ('10.10.10.4', 'Established')]
Try this: 尝试这个:
In [101]: pat = r'IP\s*\=\s*([^\n\r]*)[\r\n][^\=]*?State\s*\=\s*([^\n\r]*)'
In [102]: re.findall(pat, output, flags=re.M & re.S)
Out[102]:
[('10.10.10.1', 'Established'),
('10.10.10.2', 'Active'),
('10.10.10.3', 'Active'),
('10.10.10.4', 'Established')]
NOTE: please pay attention at @WiktorStribiżew's RegEx , which is much more elegant: 注意:请注意@WiktorStribiżew的RegEx ,它要优雅得多:
re.findall(r'(?sm)^IP = (\S+).*?^State = (\S+)',output)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.