PEM Certificate Block in PY
Match PEM-encoded certificate and key blocks, capturing the block type and base64 content.
Try it in the PY tester →Pattern
regexPY
-----BEGIN ([A-Z ]+)-----([\s\S]+?)-----END \1----- (flags: g)Python (re) code
pyPython
import re
pattern = re.compile(r"-----BEGIN ([A-Z ]+)-----([\s\S]+?)-----END \1-----")
input_text = "-----BEGIN CERTIFICATE-----\nMIIBkTCB+...\n-----END CERTIFICATE-----"
for m in pattern.finditer(input_text):
print(m.group(0))Stdlib `re` module — no third-party dependency. Works on Python 3.6+.
How the pattern works
-----BEGIN ([A-Z ]+)----- captures the block type label (e.g. CERTIFICATE, RSA PRIVATE KEY). ([\s\S]+?) lazily captures the multiline base64 body. \1 back-references the type to ensure BEGIN and END labels match. The dotAll behaviour requires [\s\S] in JS (or /s flag in newer JS) and re.DOTALL in Python.
Examples
Input
-----BEGIN CERTIFICATE-----\nMIIBkTCB+...\n-----END CERTIFICATE-----Matches
-----BEGIN CERTIFICATE-----\nMIIBkTCB+...\n-----END CERTIFICATE-----
Input
-----BEGIN RSA PRIVATE KEY-----\nMIIEow...\n-----END RSA PRIVATE KEY-----Matches
-----BEGIN RSA PRIVATE KEY-----\nMIIEow...\n-----END RSA PRIVATE KEY-----