Home > Net >  Regex match when pattern matches, but a string is missing
Regex match when pattern matches, but a string is missing

Time:02-18

I have a series of firewall configs that I need to investigate. For example:

edit "username"
    set trusthost1 123.456.789.0 255.255.255.255
    set password ENC lkajsdf;lajksd
next

and

edit "username"
    set vdom "root" "somethinghere"
next

Please note that the configs are longer than these examples and that there can be many lines with arbitrary content between the "edit" and "next" lines.

I am trying to identify any user accounts without passwords (as in the second example). I have this expression, which matches the first config and not the second (as expected):

(edit \".*\"(\n|.)*set password(\n|.)*?next)

Now I am trying to negate it, so that the second config is caught. I though I could just add "?!" inside the parenthesis, but that is not working. In regex101.com, I just end up with a bunch of purple lines (looks like null groups).

What am I missing here?

CodePudding user response:

You may use this regex in MULTILINE mode in PCRE:

^edit\h(?:.*\R(?!.*\hpassword\h)) ?next$

RegEx Demo

RegEx Details:

  • ^: Start a line
  • edit\h: Match edit followed by a whitespace
  • (?:: Start a non-capture group
    • .*: Match 0 or more of any characters
    • \R: Match a line break
    • (?!.*\hpassword\h): Negative lookahead condition to fail the match if we have line with word password surrounded by spaces on both sides
  • ) ?: End non-capture group. Repeat this group 1 or more times (lazy match)
  • next$: Match a line with next

CodePudding user response:

You can match user configs with no password using this regex:

\h edit ".*\n(?:\h  (?!next|set password).*\n)*\h next

regex101 link

  • Related