Home > Software design >  Using logic in Regex
Using logic in Regex

Time:02-12

I would like to extract data from the following configuration using Regex:

Eth 1/1/1       abc-p01.be01    up       10G      full     -
Eth 1/1/2                       down     0        full     A    1    -
Eth 1/1/3                       down     0        full     A    1    -
Eth 1/1/4       abc-02.be01     up       10G      full     -
Eth 1/1/14      dcba-08.fa01    up       10G      full     -

I've come this far:

(?P<port>Eth [\/\w\d\-] )\s [\w\d\-.] \s (?P<status>[up] )\s (?<speed>[\d\w] )

Which gave me this result (None

This is exactly what I want but it only works if the status is up. Is it possible to also match the down status (and with that the 0 speed) in the same regular expression? I've read about using logical operators in Regex (|) but I can't seem to figure it out.

CodePudding user response:

You can update the pattern with an optional part as there is no value before "down", and then match either up or down in the named group status.

Note that \w also matches \d and if you put the hyphen at the end of the character class you don't have to escape it.

(?P<port>Eth [\/\w-] )\s (?:[\w.-] \s )?(?P<status>down|up)\s (?<speed>\w )

Regex demo

  • Related