正则匹配手机号码

Friday, January 29, 2010

In [1]: import re

In [2]: test_str = 'fhdjhfdhf13888888888fdfsdfs15888888888hfdjfhjsdhfds'

In [3]: p = re.compile(r'((13[0-9]|15[0-9]|18[89])\d{8})')

In [4]: p.search(test_str).group()
Out[4]: '13888888888'

In [5]: p.search(test_str).groups()
Out[5]: ('13888888888', '138')

In [6]: p.findall(test_str)
Out[6]: [('13888888888', '138'), ('15888888888', '158')]

In [7]: [result[0] for result in p.findall(test_str)]
Out[7]: ['13888888888', '15888888888']

In [8]: [result.group() for result in p.finditer(test_str)]
Out[8]: ['13888888888', '15888888888']

In [9]: re.search('(13[0-9]|15[0-9]|18[89])\d{8}',test_str).group()
Out[9]: '13888888888'

This entry was tagged Python and regex

comments powered by Disqus

© 2009-2013 lxneng.com. All rights reserved. Powered by Pyramid

go to Top