0

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);
3
  • 3
    Seems your regular expression is not matching your input. Your regex wants 14 digits, but gets only 10. Commented Jun 7, 2016 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. Commented Jun 7, 2016 at 13:51
  • 1
    This is exactly the same question stackoverflow.com/questions/37679323/… asked with another account. Commented Jun 7, 2016 at 14:04

1 Answer 1

2

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
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.