EN VI

Regex to match --private key -- including the positive lookahead before and after?

2024-03-10 13:30:04
How to Regex to match --private key -- including the positive lookahead before and after

I want to write a regex to match this that starts with "-----BEGIN PRIVATE KEY-----" and things that end with "-----END PRIVATE KEY-----" including the "-----BEGIN PRIVATE KEY-----" and "-----END PRIVATE KEY-----".

This is my attempt:

(?ms)(?=[-]+BEGIN PRIVATE KEY[-]+)(.*?)(?=[-]+END PRIVATE KEY[-]+)

Given this:

whatever
-----BEGIN PRIVATE KEY-----
DANBgkqhkiG9w0BFQEFAASCBKkwggSlAgEA
DANBgkqhkiG9w0BFQEFAASCBKkwggSlAgEA
DANBgkqhkiG9w0BFQEFAASCBKkwggSlAgEA
s1HQDfvgtTziGzwFxggjxYvfOw==
-----END PRIVATE KEY-----
whatever

I want to get:

-----BEGIN PRIVATE KEY-----
DANBgkqhkiG9w0BFQEFAASCBKkwggSlAgEA
DANBgkqhkiG9w0BFQEFAASCBKkwggSlAgEA
DANBgkqhkiG9w0BFQEFAASCBKkwggSlAgEA
s1HQDfvgtTziGzwFxggjxYvfOw==
-----END PRIVATE KEY-----

Solution:

Your pattern is almost fine, it can be simplified:

$string = @'
whatever
-----BEGIN PRIVATE KEY-----
DANBgkqhkiG9w0BFQEFAASCBKkwggSlAgEA
DANBgkqhkiG9w0BFQEFAASCBKkwggSlAgEA
DANBgkqhkiG9w0BFQEFAASCBKkwggSlAgEA
s1HQDfvgtTziGzwFxggjxYvfOw==
-----END PRIVATE KEY-----
whatever
'@

[regex]::Match($string, '(?s)-+BEGIN PRIVATE KEY-+.*?-+END PRIVATE KEY-+').Value

Use (?si) for case insensitive. See https://regex101.com/r/LQME2Z.

If you wanted to find the string that must start with -----BEGIN PRIVATE KEY----- followed by a newline and it ends with a line starting with -----END PRIVATE KEY----- and end of the line then it would make sense to include the m flag and use the pattern:

[regex]::Match($string, '(?sm)^-+BEGIN PRIVATE KEY-+\r?$.*?^-+END PRIVATE KEY-+\r?$').Value
Answer

Login


Forgot Your Password?

Create Account


Lost your password? Please enter your email address. You will receive a link to create a new password.

Reset Password

Back to login