Regex to Parse and Validate Juniper Interface Names

Posted on July 14 2023 under networking, juniper, and regex

Basic Matching

(((irb|vlan|lo0)|(ae|em|me|fxp|ps|demux)[0-9]+|(c?[et][0-9]?|cm|[fgsx]e|[aep]t)-[0-9]+/[0-9]+/[0-9]+(:[0-9]+)?)\.[0-9]+)

Matching with Named Groups

Raw

(?P<ifl>(?P<ifd>(?:lo0|irb|vlan)|(?:ae|em|me|fxp|ps|demux)[0-9]+|(?:c?[et][0-9]?|cm|[fgsx]e|[aep]t)-(?P<fpc>[0-9]+)/(?P<pic>[0-9]+)/(?P<port>[0-9]+)(?::(?P<chan>[0-9]+))?)\.(?P<unit>[0-9]+))

Explanation

(?P<ifl>
    (?P<ifd>
        (?:lo0|irb|vlan)                     # Loopback, VLAN
        |(?:ae|em|me|fxp|ps|demux)[0-9]+     # Management, AE, Pseudowire, Demux
        |(?:c?[et][0-9]?|cm|[fgsx]e|[aep]t)  # Physical
            -(?P<fpc>[0-9]+)                 #     FPC
            /(?P<pic>[0-9]+)                 #     PIC
            /(?P<port>[0-9]+)                #     Port
            (?::(?P<chan>[0-9]+))?           #     Channel (optional)
    )\.(?P<unit>[0-9]+)                      # Logical Unit
)

Example

Using an example input of xe-0/1/2:3.100, the named groups are:

Group Description Required Example
ifl Logical Interface Name All Interfaces xe-0/1/2:3.100
ifd Physical Interface Name All Interfaces xe-0/1/2:3
unit Unit Number All Interfaces 100
fpc FPC Number Physical Interfaces 0
pic PIC Number Physical Interfaces 1
port Port Number Physical Interfaces 2
chan Channel Number   3

Interactive Example

regex 101

Python Example

>>> import re
>>> RE_INTF = re.compile(
...     r"^(?P<ifl>(?P<ifd>(?:irb|vlan|lo0)|(?:ae|em|me|fxp|ps|demux)[0-9]+|"
...     r"(?:c?[et][0-9]?|cm|[fgsx]e|[aep]t)-(?P<fpc>[0-9]+)/(?P<pic>[0-9]+)/"
...     r"(?P<port>[0-9]+)(?::(?P<chan>[0-9]+))?)\.(?P<unit>[0-9]+))$"
... )
>>> test = "xe-0/1/2:3.100"
>>> match = RE_INTF.fullmatch(test)
>>> bool(match)
True
>>> match["ifd"]
'xe-0/1/2:3'