如何使用正则表达式格式化数字 [英] How to format a number with regular expression

查看:376
本文介绍了如何使用正则表达式格式化数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到一个涉及格式化数字的问题.在巴西,我们得到了一种称为"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

这篇关于如何使用正则表达式格式化数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆