How to format a number with regular expression [duplicate]

别说谁变了你拦得住时间么 提交于 2020-05-09 17:21:07

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!