Guest User

Phone numbers to links in Python

a guest
Feb 27th, 2012
31
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.50 KB | None | 0 0
  1. import re
  2. from string import digits
  3.  
  4. PHONE_RE = re.compile('([(]{0,1}[2-9]d{2}[)]{0,1}[-_. ]{0,1}[2-9]d{2}[-_. ]{0,1}d{4})')
  5.  
  6. def numbers2links(s):
  7. result = ""
  8. last_match_index = 0
  9. for match in PHONE_RE.finditer(s):
  10. raw_number = match.group()
  11. number = ''.join(d for d in raw_number if d in digits)
  12. call = '<a href="tel:%s">%s</a>' % (number, raw_number)
  13. result += s[last_match_index:match.start()] + call
  14. last_match_index = match.end()
  15. result += s[last_match_index:]
  16. return result
  17.  
  18. >>> numbers2links("Ghost Busters at (555) 423-2368! How about this one: 555 456 7890! 555-456-7893 is where its at.")
  19. 'Ghost Busters at <a href="tel:5554232368">(555) 423-2368</a>! How about this one: <a href="tel:5554567890">555 456 7890</a>! <a href="tel:5554567893">555-456-7893</a> is where its at.'
  20.  
  21. import re
  22.  
  23. PHONE_RE = re.compile('([(]{0,1}[2-9]d{2}[)]{0,1}[-_. ]{0,1}[2-9]d{2}[-_. ]{0,1}d{4})')
  24. NON_NUMERIC = re.compile('D')
  25.  
  26. def numbers2links(s):
  27.  
  28. def makelink(mo):
  29. raw_number = mo.group()
  30. number = NON_NUMERIC.sub("", raw_number)
  31. return '<a href="tel:%s">%s</a>' % (number, raw_number)
  32.  
  33. return PHONE_RE.sub(makelink, s)
  34.  
  35.  
  36. print numbers2links("Ghost Busters at (555) 423-2368! How about this one: 555 456 7890! 555-456-7893 is where its at.")
  37.  
  38. ((00|+)?1[. -]?)?(?[2-9][0-8][0-9])?[. -]?[2-9](00|[2-9]{2})[. -]?(?!0{4})d{4}([. -]?[x#-]d+)?
  39. | A |S | | B | S | C | S | D | S | E |
Add Comment
Please, Sign In to add comment