Regex To Match Everything Except Encryption Lines

Viewed 132

I have been trying to craft a regex that matches everything in a file except for the lines that contain encrypted lines.

File example:

random text0
set private-key "-----BEGIN ENCRYPTED PRIVATE KEY-----
 MIIFHDBOBgesdfsfsf242asdasdasdasdasdasdaDDADADADASS2
 sdfsfdsfsfs342424r2aa423412edqwdadawdawa1awdsadaAAAA
 242342342da==
set private-key "-----END ENCRYPTED PRIVATE KEY-----
random text1
random text2

Using regex I want to match all random text except for the chunk of text displaying encrypted lines.

I crafted the following regex but it doesn't seem to work:

^(?!.*(\bset\s+private-key\s+"-----BEGIN\s+ENCRYPTED PRIVATE\s+KEY-----\b.*\bset private-key\s+"-----END\s+ENCRYPTED\s+PRIVATE\s+KEY-----\b)).*

----EDIT-----

File Example 2:

test12
test22
test44
        set private-key "-----BEGIN ENCRYPTED PRIVATE KEY----- 
MasdasdasdasdasEq1XnGfVONkCAggA 
KpYsdfdasdasdasdafvpFFoUanRXimMv+d9n6YiahiJ4xqPnMOelMGE dC8FRR92rpsVuZiLtgGP5A== 
-----END ENCRYPTED PRIVATE KEY-----"

test2
test3
2 Answers

One option is to match the encrypted part, and capture other lines in a capture group.

^set\s+private-key\s+"-----BEGIN\s+ENCRYPTED PRIVATE\s+KEY-----(?:\r?\n(?!set private-key).*)*\r?\nset\s+private-key.*|(.+)

The pattern matches:

  • ^ Start of string
  • set\s+private-key\s+"-----BEGIN\s+ENCRYPTED PRIVATE\s+KEY----- Match the first line
  • (?: Non capture group
    • \r?\n(?!set private-key).*)* Match all lines that do not start with set private-key
  • \r?\n Match a newline
  • set\s+private-key.* Match the line that starts with set private-key
  • | Or
  • (.+) Match 1+ times any char in group 1

See a regex demo.

Or to match multiple lines in group 1:

^set\s+private-key\s+"-----BEGIN\s+ENCRYPTED PRIVATE\s+KEY-----(?:\r?\n(?!set private-key).*)*\r?\nset\s+private-key.*|(.+(?:\r?\n(?!set\s+private-key).*)*)

Regex demo

This suits your purpose:

^(?! \w+=*$).*

See live demo.

Related