我正在處理一段代碼,將手機號碼變爲手機鏈接 - 我已經知道了,但感覺真的很髒。電話號碼到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