Go (RE2)

PEM Certificate Block in GO

Go (RE2) can't run this pattern out of the box.

Try it in the GO tester →

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.

Workaround code in Go (RE2)

goGo (workaround)
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

regexGO
-----BEGIN ([A-Z ]+)-----([\s\S]+?)-----END \1-----   (flags: g)

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-----

Same pattern, other engines

← Back to PEM Certificate Block overview (all engines)