Brazilian CPF (Cadastro de Pessoas Físicas) Regex for Java
/^(?!(\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 Java. 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 Java project — whether you're validating in a Spring Boot controller, a Jakarta EE service, or a standalone utility class.
Java Implementation
// Brazilian CPF (Cadastro de Pessoas Físicas)
// ReDoS-safe | RegexVault — Identity & PII > National Identity Numbers
import java.util.regex.Pattern;
public class BrazilianCpfCadastroDePessoasFsicasValidator {
private static final Pattern PATTERN =
Pattern.compile("^(?!(\\d)\\1{10})(?:\\d{3}\\.\\d{3}\\.\\d{3}-\\d{2}|\\d{11})$");
public static boolean validate(String input) {
return PATTERN.matcher(input).matches();
}
// Example
public static void main(String[] args) {
System.out.println(validate("123.456.789-09")); // true
}
}Test 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 Java developers because critical in Java applications since the JVM regex engine uses backtracking and is susceptible to ReDoS without careful pattern design. 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