当前位置:   article > 正文

Python之正则表达式匹配电话号码和邮箱_python正则表达式匹配电话号码和邮箱

python正则表达式匹配电话号码和邮箱

代码

  1. #! python3
  2. # phoneAndEmail.py - Finds phone numbers and email addresses on Clipboard
  3. import pyperclip
  4. import re
  5. phoneRegex = re.compile(r'''(
  6. (\d{3}|\(\d{3}\))? # area code
  7. (\s|-|\.)? # separator
  8. (\d{3}) # first 3 digits
  9. (\s|-|\.) # separator
  10. (\d{4}) # last 4 digits
  11. (\s*(ext|x|ext\.)\s*(\d{2,5}))? # extension
  12. )''', re.VERBOSE)
  13. # TODO: Create email regex.
  14. emailRegex = re.compile(r'''(
  15. [a-zA-Z0-9._%+-]+
  16. @
  17. [a-zA-Z0-9.-]+
  18. (\.[a-zA-Z]{2,4})
  19. )''', re.VERBOSE)
  20. # TODO: Find matches in Clipboard text.
  21. text = str(pyperclip.paste())
  22. matches = []
  23. for groups in phoneRegex.findall(text):
  24. # print(groups)
  25. phoneNum = '-'.join([groups[1], groups[3], groups[5]])
  26. if groups[8] != '':
  27. phoneNum += ' x' + groups[8]
  28. matches.append(phoneNum)
  29. for groups in emailRegex.findall(text):
  30. # print(groups)
  31. matches.append(groups[0])
  32. # TODO: Copy results to the Clipboard.
  33. if len(matches) > 0:
  34. pyperclip.copy('\n'.join(matches))
  35. print('Copied to clipboard:')
  36. print('\n'.join(matches))
  37. else:
  38. print('No phone number or email address found.')

 

复制以下文本后运行程序

Contact Us

No Starch Press, Inc.
245 8th Street
San Francisco, CA 94103 USA
Phone: 800.420.7240 or +1 415.863.9900 (9 a.m. to 5 p.m., M-F, PST)
Fax: +1 415.863.9950

Reach Us by Email

General inquiries: info@nostarch.com
Media requests: media@nostarch.com
Academic requests: academic@nostarch.com (Please see this page for academic review requests)
Help with your order: info@nostarch.com
Reach Us on Social Media
Twitter
Facebook
Instagram
Pinterest

 

程序输出

声明:本文内容由网友自发贡献,转载请注明出处:【wpsshop】
推荐阅读
相关标签
  

闽ICP备14008679号