-1

I'm having a problem involving formatting a number. Here in Brazil we got a type of document called "CPF", which is a type of personal ID every citizen have.

So here is an example of a correctly formatted CPF number: 096.156.487-09

I'm trying to use a regular expression to format a string containing a CPF number, but I'm having a hard time at it. My current code is returning the unformatted numbers.

For instance: It should output 123.456.789-0 but instead I'm getting 1234567890.

This is my current code:

    String cpf ="09551130401";
    cpf = cpf.replaceAll("(\\d{2})(\\d{3})(\\d{3})(\\d{4})(\\d{2})", "$1.$2.$3-$4");
    System.out.println(cpf);
Shafizadeh
  • 9,960
  • 12
  • 52
  • 89
Walter White
  • 1
  • 1
  • 1
  • 3
    Seems your regular expression is not matching your input. Your regex wants 14 digits, but gets only 10. – wallenborn Jun 07 '16 at 13:51
  • 2
    Have you tried to count the amount of digits in `09551130401` to see if it matches your regex? Do that and you'll be surprised. – Tom Jun 07 '16 at 13:51
  • 1
    This is exactly the same question http://stackoverflow.com/questions/37679323/formating-cpf-with-regex-java asked with another account. – Tunaki Jun 07 '16 at 14:04

1 Answers1

1

I'm not sure I get your right .. But maybe you're looking for this pattern:

"(\\d{3})(\\d{3})(\\d{3})(\\d{2})"

And replace with $1.$2.$3-$4.

Online Demo


Full Code:

String cpf ="09551130401";
cpf = cpf.replaceAll("(\\d{3})(\\d{3})(\\d{3})(\\d{2})", "$1.$2.$3-$4");
System.out.println(cpf);
//=> 095.511.304-01
Community
  • 1
  • 1
Shafizadeh
  • 9,960
  • 12
  • 52
  • 89