Python regex to parse router config

Viewed 119

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 '!'?

2 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', '')].

This regex works based on your example

interface (\w+)$[\w\s]*?address ([\d.\/]+)

It returns 2 groups,

Vlan1
1.2.3.4/30

See it working on regex101.com.

Related