PEM Certificate Block in JS
Match PEM-encoded certificate and key blocks, capturing the block type and base64 content.
Try it in the JS tester →Pattern
regexJS
-----BEGIN ([A-Z ]+)-----([\s\S]+?)-----END \1----- (flags: g)JavaScript / ECMAScript code
jsJavaScript
const re = new RegExp("-----BEGIN ([A-Z ]+)-----([\\s\\S]+?)-----END \\1-----", "g");
const input = "-----BEGIN CERTIFICATE-----\\nMIIBkTCB+...\\n-----END CERTIFICATE-----";
const matches = [...input.matchAll(re)];
console.log(matches.map(m => m[0]));Uses `String.prototype.matchAll` for global iteration (Node 12+ / all modern browsers).
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-----