Brazilian CNPJ (Cadastro Nacional da Pessoa Jurídica) Regex for Java
/^(\d{2})\.?(\d{3})\.?(\d{3})/?([0-9]{4})-?(\d{2})$/What this pattern does
This page provides a well-structured, multi-part regular expression for matching brazilian cnpj (cadastro nacional da pessoa jurídica), 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 CNPJ (Cadastro Nacional da Pessoa Jurídica)
// ReDoS-safe | RegexVault — Identity & PII > National Identity Numbers
import java.util.regex.Pattern;
public class BrazilianCnpjCadastroNacionalDaPessoaJurdicaValidator {
private static final Pattern PATTERN =
Pattern.compile("^(\\d{2})\\.?(\\d{3})\\.?(\\d{3})/?([0-9]{4})-?(\\d{2})$");
public static boolean validate(String input) {
return PATTERN.matcher(input).matches();
}
// Example
public static void main(String[] args) {
System.out.println(validate("11.222.333/0001-81")); // true
}
}Test Cases
Matches (Valid) | Rejects (Invalid) |
|---|---|
11.222.333/0001-81 | 11.222.333/001-81 |
11222333000181 | 11222333000181234 |
00.000.000/0001-91 | 11.222.333/0001-8 |
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
CNPJ branches allow one company to have many CNPJs. 11.222.333/0001-81 and 11.222.333/0002-62 are the same company, different branches. Store the full 14-digit CNPJ to distinguish branches.
Technical Notes
CNPJ format: 14 digits (8-digit base + 4-digit branch + 2 check digits). Branch 0001 is the main establishment; branches 0002+ are subsidiaries. All-same-digit numbers are invalid. Check digits use weighted sums similar to CPF but different weights.
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