Format CPF or CNPJ field using Regex [duplicate]

3

I would like a regular expression (REGEX) to format the CPF or CNPJ field

This is the code I've come so far:

    String cpf ="09551130401";
    cpf = cpf.replaceAll("(\d{2})(\d{3})(\d{3})(\d{4})(\d{2})", "$1.$2.$3-$4");
    System.out.println(cpf);
    
asked by anonymous 07.06.2016 / 13:58

1 answer

8

CNPJ: (^ \ d {2}. \ d {3}. \ d {3} / \ d {4}

CPF: (^ \ d {3} \ x2E \ d {3} \ x2E \ d {3} \ x2D \

Using Bean Validation, you can set a default for your variable.

@Pattern(regexp = "(^\d{3}\x2E\d{3}\x2E\d{3}\x2D\d{2}$)")
private String cpf;

I searched these expressions here and tested them on this site .

    
07.06.2016 / 15:31