Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python regex to parse router config

Tags:

python

regex

I can't seem to get my regex to work quite right. There are several edge cases that I can't seem handle. A standard router config looks like this:

interface Vlan1

  description

  ip address 1.2.3.4/30

!

The interface starts with 'interface NAME' and ends with !. I would like my regex to capture the interface name 'Vlan1' and the ip '1.2.3.4/30'

Here is what I have that almost works: re.compile(r"interface (.*)(?:[^!].*\n){1,50}? (?:no )?ip(?: v4| v6)? address(.*?)\n")

Edge cases:

  • I don't know how many lines the ip will be from the interface name (50 should be enough)
  • sometimes the ip address line might be: 'ip v4 address', 'ip v6 address', or 'no ip address'

I think I have all of that working, but when there is an interface like below:

interface Vlan2
!

It breaks everything. Is there something else I can be doing to capture between 'interface' and '!'?

like image 759
frustrated2021 Avatar asked May 26 '26 03:05

frustrated2021


1 Answers

Because of the non-optional parts , ip and address, your regex doesn't match the empty interface section. Because of its complexity, I started anew and suggest this simpler one:

re.compile(r"^interface (\w+)(?:[^!]*?address (\S+))?.*?!", re.M+re.S)

With your two examples, findall() would yield [('Vlan1', '1.2.3.4/30'), ('Vlan2', '')].

like image 153
Armali Avatar answered May 27 '26 15:05

Armali