我正在处理一段代码,将手机号码变为手机链接 - 我已经知道了,但感觉真的很脏。电话号码到Python中的链接
import re
from string import digits
PHONE_RE = re.compile('([(]{0,1}[2-9]\d{2}[)]{0,1}[-_. ]{0,1}[2-9]\d{2}[-_. ]{0,1}\d{4})')
def numbers2links(s):
result = ""
last_match_index = 0
for match in PHONE_RE.finditer(s):
raw_number = match.group()
number = ''.join(d for d in raw_number if d in digits)
call = '<a href="tel:%s">%s</a>' % (number, raw_number)
result += s[last_match_index:match.start()] + call
last_match_index = match.end()
result += s[last_match_index:]
return result
>>> numbers2links("Ghost Busters at (555) 423-2368! How about this one: 555 456 7890! 555-456-7893 is where its at.")
'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.'
反正我有可能重组正则表达式或我使用,使这种清洁的正则表达式的方法?
更新
为了澄清,我的问题是不是我的正则表达式的正确性 - 我意识到,这是有限的。相反,我想知道是否有人对替代电话号码链接的方法有任何意见 - 无论如何,我可以使用re.replace
或类似的东西,而不是我有的字符串hackery?
这是约100倍更清晰 - 谢谢三联! – 2008-12-22 21:14:55