Raeven
Raeven

Reputation: 11

Regex matching Cisco interface

I am trying to match Cisco's interface names and split it up. The regex i have so far is:

(\D+)(\d+)(?:\/)?(\d+)?(?:\.)?(\d+)?

This matches:

FastEthernet9
FastEthernet9/5
FastEthernet9/5.10

The problem i have is that it also matches:

FastEthernet9.10

Any ideas on how to make it so it does not match? Bonus points if it can match:

tengigabitethernet0/0/0.20

Edit:

Okay. I am trying to split this string up into groups for use in python. In the cisco world the first part of the string FastEthernet is the type of interface, the first zero is the slot in the equipment the zero efter the slash is the port number and the one after the dot is a sub-interface.

Because of how regex works i can't get dynamic groups like (?:\/?\d+)+ to match all numbers in /0/0/0 by them selves, but i only get the last match.

My current regex (\D+)(\d+)(?:((?:\/?\d+)+)?(?:(?:\.)?(\d+))?) builds on murgatroid99's but groups all /0/0/0 together, for splitting in python.

My current result in python with this regex is [('tengigabitethernet', '0', '/0/0', '10')]. This seems to be how close i can get.

Upvotes: 0

Views: 10830

Answers (1)

murgatroid99
murgatroid99

Reputation: 20297

The regular expression for matching these names (Removing unnecessary capturing groups for clarity) is:

\D+\d+((/\d+)+(\.\d+)?)?

To break it up, \D+ matches the part of the string before the first number (such as FastEthernet and \d+ matches the first number (such as 10). Then the rest of the pattern is optional. /\d+ matches a forward slash followed by a number, so (/\d+)+ matches any number of repetitions of that (such as /0/0). Finally, (\.\d+)? optionally matches the period followed by a number at the end.

The important difference that makes this pattern match your specification is that in the final optional group, we get at least one (/\d+) before the (\.\d).

Upvotes: 1

Related Questions