分享

Python3 两种方式查找字符串里的电话号码

 大傻子的文渊阁 2020-02-14

利用非正则表达式在字符串中查找电话号码。

查号码.py

  1. def isPhoneNumber(text):
  2. if len(text) !=12:
  3. return False
  4. for i in range(0,3):
  5. if not text[i].isdecimal():
  6. return False
  7. if text[3] != '-':
  8. return False
  9. for i in range(4,7):
  10. if not text[i].isdecimal():
  11. return False
  12. if text[7] != '-':
  13. return False
  14. for i in range(8,12):
  15. if not text[i].isdecimal():
  16. return False
  17. return True
  18.  
  19. print('415-555-4242 is a phone number:')
  20. print(isPhoneNumber('415-555-4242'))
  21. print('Moshi moshi is a phone number:')
  22. print(isPhoneNumber('Moshi moshi'))
  23.  
  24. message = 'Call me at 415-555-3333 tomorrow. 415-555-4223 is my office.'
  25. for i in range(len(message)):
  26. chunk = message[i:i+12]
  27. if isPhoneNumber(chunk):
  28. print('Phone number found: ' + chunk)
  29. print('Done')

运行结果

415-555-4242 is a phone number:
True
Moshi moshi is a phone number:
False
Phone number found: 415-555-3333
Phone number found: 415-555-4223
Done

借助正则表达式在字符串中查找电话号码。

  1. >>> import re
  2. >>> phoneNumRegrx = re.compile(r'\d\d\d-\d\d\d-\d\d\d\d')
  3. >>> mo = phoneNumRegrx.search('My number is 415-555-4242.')
  4. >>> print("phone number found: "+ mo.group())
  5. phone number found: 415-555-4242
  6. >>>

借助正则表达式在字符串中查找带区号的电话号码。

  1. >>> import re
  2. >>> phoneNumRegrx = re.compile(r'(\(\d\d\d\)) (\d\d\d-\d\d\d\d)')
  3. >>> mo = phoneNumRegrx.search('My number is (415) 555-4242.')
  4. >>> mo.group(1)
  5. '(415)'
  6. >>> mo.group(2)
  7. '555-4242'
  8. >>> mo.group()
  9. '(415) 555-4242'
  10. >>>

转载请注明:大学助 » Python3 两种方式查找字符串里的电话号码

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多