使用特定掩码正则表达式python格式化数字号码 [英] Format number number with specific mask regex python

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

问题描述

我需要使用特定掩码格式化一个数字: 9.9.9.9.99.999 ,具体取决于数字字符串的长度。

例如:

I need to format a number with a specifc mask: 9.9.9.9.99.999, depending on the length of number string.
For example:

- 123456789 => 1.2.3.4.56.789
- 123456    => 1.2.3.4.56
- 1234      => 1.2.3.4
- 123       => 1.2.3
- 12        => 1.2

输入中不会出现数字字符串,其中包含7或8位数字。

It will not occur a number string with 7 or 8 digits in the input.

这怎么能用regex来实现,最好在python中?

How could that be implemented with regex, preferably in python?

在此先感谢。

推荐答案

您可以使用以下模式:

You can use this pattern:

(?:(?<=^\d)|(?<=^\d{2})|(?<=^\d{3})|(?<=^\d{4})|(?<=^\d{6}))(?=\d)

作为替换。

示例:

re.sub(r'(?:(?<=^\d)|(?<=^\d{2})|(?<=^\d{3})|(?<=^\d{4})|(?<=^\d{6}))(?=\d)', '.', yourstr)

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

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