livy111
livy111

Reputation: 131

Regex Match if string does not exist (multi-line)

Trying to match if a word does NOT exist. I have done this before but am having issues trying to apply same concepts to my current regex pattern. The below pattern is from a cisco switch, which uses "!" as a separator between interfaces. The pattern matches if vlan1 exists and contains "no shutdown" in its multi-line config block.

(?mi)vlan1[^\d][^!]*?((^.|^)no shutdown)

The issue is that I am trying to also match when the interface vlan1 config block does NOT have the string "shutdown". This is required because both the "no shutdown" and the absence of "shutdown" (without "no") indicate that interface vlan1 is enabled.

For example, I am anticipating something similar to the below pattern, which does not work:

(?mi)vlan1[^\d][^!]*?(^.|^)(no shutdown|(?!shutdown))

The result should match ONLY if either "no shutdown" or the absence of "shutdown" exists.

See work here: https://regex101.com/r/vhE3xm/1

Upvotes: 1

Views: 959

Answers (2)

livy111
livy111

Reputation: 131

I figured it out, much thanks to @WiktorStribiżew for the assist. here is what I used

(?mi).*vlan1[^\d](?:(?!(.|\n)[^!]*(?<!no\W)shutdown))

This will ONLY match if "vlan1" exists AND it does NOT contain "shutdown" in its script block (between two '!' symbols). I knew it would be a fairly simple solution. Any way you can optimize it? It currently takes awhile to complete. regex101.com/r/gYTP6n/1

Note: You have to remove the word "shutdown". or any letter within it. My goal is for it NOT to match, because a match would be a fail in my audit

Upvotes: 0

wp78de
wp78de

Reputation: 18980

I suggest to use the opposite logic: Check if the Vlan1 interface has been shut down properly:

(Vlan\d+)(?:(\n(\s(\[\w-=<>\])+)+)+)(?=\n\sshutdown)

$1 contains Vlan1 if shutdown was found in the following block.

Upvotes: 1

Related Questions