问题
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);
回答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
来源:https://stackoverflow.com/questions/37681277/how-to-format-a-number-with-regular-expression