2

How to use regex with different pattern in a multiline string in python

str1 = ''''
  interface is up
  admin state is up
  mtu is 1500

 '''

 str2 = 'interface is up admin state is up'

 pat = re.compile(r"interface is ([A-za-z]+) admin state is ([A-za-z]+)")

 matches = pat.finditer(str2)

for match in matches:
    print match.group()
    print match.group(1)
    print match.group(2)

the above regex pattern works for str2 (which doesn;t have newline) but not for str1 which has the same text but with newline.

I tried using re.M as well but that also doesn't seem to work.

I wanted to filter the interface status, admin status and mtu with different patterns on a multiline string.

1
  • replace newlines with space for str1. Commented Jul 5, 2018 at 13:05

1 Answer 1

1

Try changing your pattern to optionally include newlines and whitespaces before admin state

r"interface is ([A-za-z]+)[\s\r\n]*admin state is ([A-za-z]+)"

Example

pat = re.compile(r"interface is ([A-za-z]+)[\s\r\n]*admin state is ([A-za-z]+)", re.MULTILINE)
matches = pat.finditer(str1)
for match in matches:
    print match.groups()
# ('up', 'up')
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks a lot. One more query. if the string is multiline with : in it, when it used something like this [\s\w,:]+. it selected almost all the lines. looks like it became greedy. how do I restrict it not to go beyond that line?
Adding a ? after the * or + makes it non-greedy. So try using [\s\w,:]+?

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.