Format CPF or CNPJ field using Regex

Asked

Viewed 27,947 times

3

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

This is the code I’ve come up with 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);

1 answer

9


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

CPF: (^\d{3} x2E d{3} x2E d{3} x2D d{2}$)

Using Validation Bean, 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 website.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.