How to search multiple lines using regex in Python

Viewed 65

I am looking for Python multiple line extraction using regex.

clock timezone EST -2 0

clock summer-time EDT recurring

!

ip dhcp snooping vlan 1-4094

no ip dhcp snooping information option

ip dhcp snooping

no ip domain-lookup

ip domain-name abc.com

ip device tracking probe auto-source override

!

crypto pki trustpoint TP-self-signed-142154678

Regular expression I tried:

match = re.search(r"^ip dhcp.*/s+.*/s+.*/s+.*/s+.*/s+.*override",filename,flags=re.M).group(0)

But the problem is the number of lines are not fixed as it may be different on other devices as some commands could be missing.

So, what I am looking for here is to write a expression where I just mention the start point in the file and the end point and whatever there is the middle can be extracted. If I mention \s+ then I am not sure how many lines are there in the middle as .* can't go to another line.

I am looking for something in the regex or any other solution where I can extract the configuration from starting point to end point as mentioned above irrespective of the lines missing in between.

1 Answers

You can use

re.search(r"^ip dhcp.*(?:\n(?!!).*)*\n.*override",filename,flags=re.M)
re.search(r"(?m)^ip dhcp.*(?:\n(?!!).*)*\n.*override",filename)

Note: if override should be matched as a whole word, enclose it with \b, i.e. (?m)^ip dhcp.*(?:\n(?!!).*)*\n.*\boverride\b.

The pattern matches

  • (?m) - the re.M inline option (makes the ^ match start of any line)
  • ^ - line start
  • ip dhcp - a fixed string
  • .* - the rest of the line
  • (?:\n(?!!).*)* - zero or more lines if not starting with !
  • \n - a newline char
  • .*override - any zero or more chars other than line break chars, as many as possible, and then override.

See the regex demo.

On the Python side, it is not safe to directly chain the .group() method call after re.search. It is safer to get the match first, and if it succeeded, access the group value:

match = re.search(r"(?m)^ip dhcp.*(?:\n(?!!).*)*\n.*override",filename)
if match:
    print(match.group())
Related