I am a network engineer with limited programming skills, I use a tool called dnGREP that is based in NET4.0 for searching text within common text files. What I need to do as part of my job is finding commands applied to the configuration of any interface.
My idea is trying to find the correct REGEX limited by two items. But there are several issues that I am having while trying to build an efficient REGEX.
Taking the following string from a "show running-configuration" of a Cisco device:
interface GigabitEthernet0/0/0/1.1982
ipv4 address 10.111.193.125 255.255.255.252
ipv4 unreachables disable
load-interval 30
dot1q vlan 1982
!
interface GigabitEthernet0/0/0/1.1983
ipv4 address 10.113.193.125 255.255.255.252
ipv4 unreachables disable
load-interval 30
dot1q vlan 1983
!
interface GigabitEthernet0/0/0/2.1982
ipv4 address 10.111.193.129 255.255.255.252
ipv4 unreachables disable
load-interval 30
find me
dot1q vlan 1982
!
As you can see, the interface configuration can be limited by 2 items.
Start Item:
interface
End Item:
!
Given a string I want a REGEX that matches the string along with the interface context.
Conditions:
- The REGEX should return the interface context delimited by "interface" until "!".
- The REGEX should print ALL the ocurrences
This is my REGEX so far:
^interface([\s\S]*?)find me([\s\S]*?)!
Breakdown:
^interface–"Start searching when "interface" is the beginning of the line."
([\s\S]*?—-"Search for any character including new line"
find me—-"find me is the string/command that I am looking for"
([\s\S]*?!—-"Keep printing until you find the !"
Of course above REGEX does not do what I expect. It should return this only:
interface GigabitEthernet0/0/0/2.1982
ipv4 address 10.111.193.129 255.255.255.252
ipv4 unreachables disable
load-interval 30
find me
dot1q vlan 1982
!
Instead it returns all the stuff after the first interface is found which is not what I want.
I know why this is happening but I don’t know how to correct it.
"Regex starts searching for find me when the first interface is found however it should STOP if string find me is not found when reaching a ! declaring a no match HOWEVER it should continue until the end of the file and print all the interface contexts that contains the string find me"
I hope my explanation is clear. Any help is really appreciated =).
Try the following regex:
Explanation:
interface\s*– the word “interface” followed by 0 or more white spaces;(?<text>[^!]+find me[^!]+)– the grouptextcontaining any character except “!”, 1 or more repetitions and the string “find me”;(?:!)?– match the “!” character, but don’t capture it, 0 or 1 repetitions (to cater for the last paragraph, if the character is missing).