2014-02-12 73 views
0

用户可以输入在任何下列格式中的电话号码:格式化的手机号码,国际格式

  1. 07xxxxxxxxx

  2. 00447xxxxxxxxx

  3. 447xxxxxxxxx

  4. +447xxxxxxxxx

我需要帮助创建一个函数,将采取上述任何格式的数字并将其作为国际格式返回+447xxxxxxxxx

这是我迄今为止

def _clean_mobile(mobile): 

    import re 
    if re.match('^+44', mobile): 
     return mobile 
    elif re.match('^44', mobile): 
     return "+" + mobile 
+0

和你被卡住了,因为? – njzk2

+1

对不起,但前面的编辑​​在各方面都是错误的。当问题已经被标记并将特定于版本的标签移动到帖子正文中时,建议的编辑向后不必要地添加语言名称作为前缀,然后将有序列表更改为无序列表明显的原因......然后审稿人重新介绍了一个在早期编辑中修复的错字!我真的无法理解人们在编辑或审阅建议编辑时有时在想什么。 :| –

+0

@ njzk2,好吧,有几个原因,我不是100%确定这是否是最好的方法,我确信使用这样的re.match不会帮助我说如果将来我加0771或者其他的东西。 – Prometheus

回答

2

工作例如:http://ideone.com/ErL7Y4

def standardizePhoneNumber(mobile): 
import re 
    valid_prefixes = '[+447|447|00447|07]' 
result = re.match('^' + valid_prefixes + '*([0-9]{9})$', mobile) 
if result: 
    return '+447' + result.group(1) 
else: 
    return None # invalid format 

print standardizePhoneNumber('07111111111') 
print standardizePhoneNumber('00447111111111') 
print standardizePhoneNumber('447111111111') 
print standardizePhoneNumber('+447111111111') 
print standardizePhoneNumber('456789456') 
2
import re 
FORMATS = ['^07', '^00447', '^447', '^\+447'] 
def sanitize(mobile): 
    mobile = re.sub('\s+', '', mobile) # strip whitespaces 
    for format in FORMATS: 
     if re.match(format, mobile): 
      return re.sub(format + '(\d{9})', '+447\g<1>', mobile) 
    return mobile 

sanitize('00447123456789') # +447123456789 
sanitize('07123456789')  # +447123456789 
sanitize('447123456789')  # +447123456789 
sanitize('+44 712 345 67 89')# +447123456789 
1

下面是使用Python的format方法可能是简单的解决方案:

numbers= ['07345216342', '00447345216342', '447345216342', '+447345216342'] #input 
for i in numbers: 
    print '+447{0:0=9d}'.format(int(str(i)[-9:])) 

OUTP ut:

+447345216342 
+447345216342 
+447345216342 
+447345216342