PEM Certificate Block
Match PEM-encoded certificate and key blocks, capturing the block type and base64 content.
Try it in RegexPro →Available in
JavaScript / ECMAScript code
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).
Python (re) code
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+.
Why it doesn't work in GO
Go's RE2 engine doesn't support backreferences (`\1`, `\2`, …) for the same linear-time reason.
Approach
Match the candidate substring with a single capture, then verify the duplication in code; or use JS / Python which both support backreferences.
Read the full guide →Workaround code in Go (RE2)
package main
import (
"fmt"
"regexp"
)
// RE2 doesn't support backreferences. The fix: capture the candidate
// substring once, then verify the duplication in Go code.
//
// Example: instead of `(\w+)\s+\1` (duplicate words), capture two
// adjacent words and compare them.
func main() {
re := regexp.MustCompile(`\b(\w+)\s+(\w+)\b`)
input := "the cat cat ran ran fast"
for _, m := range re.FindAllStringSubmatch(input, -1) {
if m[1] == m[2] { // the backreference equality, in code
fmt.Println(m[0])
}
}
}Capture the candidate substrings as separate groups, then compare them in Go code instead of via a backreference.
Pattern
-----BEGIN ([A-Z ]+)-----([\s\S]+?)-----END \1----- (flags: g)Raw source: -----BEGIN ([A-Z ]+)-----([\s\S]+?)-----END \1-----
How it works
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-----
Common use cases
- •TLS certificate extraction from config files
- •Secret scanning for accidentally committed private keys
- •Certificate chain parsing in mTLS tooling
- •Automated cert rotation pipelines
Related patterns
PEM Private Key Block
SecurityMatch PEM-encoded private key blocks across the common variants (RSA, EC, DSA, OpenSSH, encrypted, PGP).
AWS Access Key ID
SecurityMatch AWS access key IDs (both long-term AKIA and temporary ASIA prefixes).
Bearer Token (Authorization Header)
SecurityMatch Bearer token values from HTTP Authorization headers, capturing the raw token string.
JWT Token
SecurityMatch JSON Web Tokens (JWTs) — three base64url-encoded segments separated by dots.