1

I am new to Python regex. I trying to get below lst from the output.

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

[('10.10.10.1', 'Established'), ('10.10.10.2', 'Active'), ('10.10.10.3', 'Active'), ('10.10.10.4', 'Established')]
4
  • 1
    Use re.findall(r'(?sm)^IP = (\S+).*?^State = (\S+)',output) if your input is well formatted and there is a State for each IP. Commented Aug 19, 2017 at 17:39
  • @WiktorStribiżew What is for (?sm). Could you please let me know ? Commented Aug 19, 2017 at 17:46
  • re.DOTALL + re.MULTILINE Commented Aug 19, 2017 at 17:47
  • @WiktorStribiżew Thanks a lot...new learning for me :) Commented Aug 19, 2017 at 17:49

1 Answer 1

2

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:

re.findall(r'(?sm)^IP = (\S+).*?^State = (\S+)',output)
Sign up to request clarification or add additional context in comments.

6 Comments

Why [\r\n]? As far as I know, all Unix systems use just \n, while Microsoft uses a sequence \r\n, but nobody uses \r alone.
@Błotosmętek, yes, but in [] RegEx we specify a list of symbols in any order... ;-)
@Błotosmętek \r is a MacOS line break style.
Yes, I know how [] works - [\r\n] matches either \n (Unix) or \r (???); it does not match \r\n (Microsoft) though… care to explain?
@WiktorStribiżew funny, I thought MacOS X uses \n like all other Unix variants…
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.