如何使用正则表达式格式化数字

问题描述:

我遇到一个涉及格式化数字的问题.在巴西,我们得到了一种称为"CPF"的文件,这是每个公民都拥有的一种个人身份证.

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.

这是正确格式的CPF编号的示例:096.156.487-09

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

我正在尝试使用正则表达式来格式化包含CPF数字的字符串,但是我很难过.我当前的代码返回未格式化的数字.

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.

例如:它应该输出123.456.789-0,但我却得到了1234567890.

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

这是我当前的代码:

    String cpf ="09551130401";
    cpf = cpf.replaceAll("(\\d{2})(\\d{3})(\\d{3})(\\d{4})(\\d{2})", "$1.$2.$3-$4");
    System.out.println(cpf);

我不确定我是否正确..但是也许您正在寻找这种模式:

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

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

并替换为$1.$2.$3-$4.

完整代码:

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