Brazilian CPF (Cadastro de Pessoas Físicas) Regex for Go
/^(?!(\d)\1{10})(?:\d{3}\.\d{3}\.\d{3}-\d{2}|\d{11})$/What this pattern does
This page provides a comprehensive, battle-tested regular expression for matching brazilian cpf (cadastro de pessoas físicas), ported and verified for Go. Identity and credential patterns need both correctness and safety, since they're frequent targets for adversarial input. The snippet below is ready to drop into your Go project — whether you're validating in a Gin handler, a gRPC service, or a command-line tool.
Go Implementation
// Brazilian CPF (Cadastro de Pessoas Físicas)
// ReDoS-safe | RegexVault — Identity & PII > National Identity Numbers
package validation
import "regexp"
var brazilianCpfCadastroDePessoasFsicasRe = regexp.MustCompile(`^(?!(\d)\1{10})(?:\d{3}\.\d{3}\.\d{3}-\d{2}|\d{11})$`)
func ValidateBrazilianCpfCadastroDePessoasFsicas(s string) bool {
return brazilianCpfCadastroDePessoasFsicasRe.MatchString(s)
}
// Example
// fmt.Println(ValidateBrazilianCpfCadastroDePessoasFsicas("123.456.789-09")) // trueTest Cases
Matches (Valid) | Rejects (Invalid) |
|---|---|
123.456.789-09 | 123.456.789-0 |
12345678909 | 123.456.7890-9 |
987.654.321-00 | — |
12345678900 | — |
111.111.111-11 | — |
When to use this pattern
This pattern is drawn from the Identity & PII > National Identity Numbers category and carries a ReDoS-safe certification. That matters for Go developers because Go's RE2 engine is inherently safe from catastrophic backtracking, but this pattern has been additionally verified for correctness. RegexVault audits patterns against known backtracking attack vectors, ensuring you have the necessary context before using this regex in a high-stakes production environment.
Common Pitfalls
Must validate the check digits — all-same-digit numbers (000.000.000-00 through 999.999.999-99) pass the format check but are explicitly invalid. Use a CPF validation library.
Technical Notes
CPF is 11 digits with two check digits computed via weighted sum. All-same-digit CPFs (111.111.111-11) are structurally valid but officially invalid. Check digits: first is 10-(sum × weights 10-2 mod 11), second uses the same method with weights 11-2.
Have a pattern that belongs in the vault?
Submit it for review — community-verified patterns get credited to your GitHub handle. Free submissions join the queue. Priority review available for $15.
Submit a Pattern