格式化数字与特定掩码正则表达式python

pbo*_*pbo 6 python regex format mask string-formatting

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

- 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
Run Code Online (Sandbox Code Playgroud)

它不会出现输入中带有7或8位数字的数字字符串.

如何使用正则表达式实现,最好是在python中?

提前致谢.

Cas*_*yte 9

您可以使用此模式:

(?:(?<=^\d)|(?<=^\d{2})|(?<=^\d{3})|(?<=^\d{4})|(?<=^\d{6}))(?=\d)
Run Code Online (Sandbox Code Playgroud)

.作为替代.

例:

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


Luk*_*raf 5

它必须是正则表达式吗?

num = "123456789"

def fmt(num):
    block1 = list(num[:4])
    block2 = len(num) > 4 and [num[4:6]] or []
    block3 = len(num) > 6 and [num[6:]] or []
    return ".".join(block1 + block2 + block3)

print fmt(num)
Run Code Online (Sandbox Code Playgroud)

我相信我在两年后仍然理解这一点。不太确定正则表达式。