This page was exported from phaq [ http://phaq.phunsites.net ]
Export date: Tue Jun 18 5:44:39 2019 / +0000 GMT
A project I'm currently working on involges much Regurlar Expressions trickery to parse values from Cisco's running configuration.
Here's how to extract a complete interface block not in 'shutdown' state.

Imagine a Cisco configuration block like this:


!
interface BRI0
no ip address
encapsulation hdlc
shutdown
!


And here the same again without the 'stutdown' statement:


!
interface BRI0
no ip address
encapsulation hdlc
!


Thinking about a case where you want to extract just these blocks from multiple config files, but only if they don't contain the 'shutdown' statement. The solution to this with Regular Expressions is called negative look-ahead, so to speak "match something not followed by something else".

The trick is to make anchored matches within the context we're searching.
Looking at the block, we get multiple anchors:


  • 'interface' following by the interface name and line feed/carriage return as our beginning marker

  • a line starting with an exclamation mark marking the end of the block

  • any number of lines in between starting with at least 1 whitespace character



So an extended expression, which would match just this criteria looks like this:

/^interface .*[rn]+(?:^s.*[rn])+(?:^![rn]+)+/m


This would match any interface configuration block.
Now if we want only the interface in 'no shutdown' state, we add a negative look-ahead which can be spoken of as this:


  • any number of lines in between starting with at least 1 whitespace character NOT followed by the word 'shutdown'



Thus, our expression now looks like this:

/^interface .*[rn]+(?:^s(?!shutdown).*[rn])+(?:^![rn]+)+/m


This will return just the matches for interfaces in 'no shutdown' state.
Powered by [ Universal Post Manager ] plugin. HTML saving format developed by gVectors Team www.gVectors.com