简体   繁体   English

正则表达式省略前导零

[英]RegEx Omits Leading Zeroes

I am trying to write a relatively simply function in Python that parses phone number. 我试图用Python编写一个相对简单的函数来解析电话号码。 At the moment, the RegEx is giving me trouble. 目前,RegEx给我带来麻烦。 Namely, it omits leading zeroes, which I would like to keep. 即,它忽略了我想保留的前导零。

How can I modify it so the leading zeroes are kept? 如何修改它,以便保留前导零? The pattern also keeps 4 items in the end, which is undesired. 该模式最后还会保留4个项目,这是不希望的。 At most three digits in the last block are desired. 最后一个块中最多需要三位数字。

phone_number = re.sub("(\d{3})(?=(\d)+(?!\d))", r"\1-", "%d" % int(clean_number[:-1])) + clean_number[-1]

What I would like is something like this: 我想要的是这样的:

Input: 00112223344 Output: 001-122-233-44 Input: 00112223344 Output: 001-122-233-44

Try this - 尝试这个 -

phone_number  = re.sub(r'(\d{3})', r'\1-', phone_number)

It should work. 它应该工作。 Here is the demo 这是演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM