python正则匹配数字_使用特定掩码正则表达式python格式化数字号码

该博客介绍如何使用Python的正则表达式库(re)将不同长度的数字字符串格式化为9.9.9.9.99.999的模式。示例包括将-123456789转换为1.2.3.4.56.789,-123456转换为1.2.3.4.56,-1234转换为1.2.3.4,以及更短的数字。提供的正则表达式模式用于根据输入数字的长度插入点号。
摘要由CSDN通过智能技术生成

1586010002-jmsa.png

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

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

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

Thanks in advance.

解决方案

You can use this pattern:

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

with . as replacement.

example:

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值