python - 美国格式的电话号码到 Python 中的链接

标签 python regex mobile-website phone-number

我正在编写一段代码,将电话号码转换为手机链接 - 我知道了,但感觉真的很脏。

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 ?

最佳答案

第一次尝试很不错 :) 我认为这个版本更具可读性(而且可能稍微快一点)。这里要注意的关键是 re.sub 的使用。让我们远离讨厌的匹配索引......

import re

PHONE_RE = re.compile('([(]{0,1}[2-9]\d{2}[)]{0,1}[-_. ]{0,1}[2-9]\d{2}[-_.  ]{0,1}\d{4})')
NON_NUMERIC = re.compile('\D')

def numbers2links(s):

   def makelink(mo):
      raw_number = mo.group()
      number = NON_NUMERIC.sub("", raw_number)
      return '<a href="tel:%s">%s</a>' % (number, raw_number)

   return PHONE_RE.sub(makelink, s)


print numbers2links("Ghost Busters at (555) 423-2368! How about this one: 555 456 7890! 555-456-7893 is where its at.")

注:在我的实践中,我没有注意到预编译简单的正则表达式(就像我正在使用的两个)有多少加速,即使您使用它们数千次也是如此。 re 模块可能有某种内部缓存 - 没有费心阅读源代码和检查。

此外,我用另一个 re.sub() 替换了您检查每个字符以查看它是否在 string.digits 中的方法,因为我认为我的版本更具可读性,不是因为我确定它的性能更好(尽管它可能)。

关于python - 美国格式的电话号码到 Python 中的链接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/385632/

相关文章:

Python,使用列表,找到最大序列长度

javascript - javascript正则表达式的验证

jquery - 修复 RegEx 中的 JSLint 擒纵机构不良警告

javascript - 用于验证用户定义的条件评估逻辑的正则表达式

python - Python 中的 String.strip()

python - TensorFlow TypeError : Fetch argument None has invalid type <type 'NoneType' >?

python - Matplotlib 中的非 ASCII 字符

javascript - 如何在手机浏览器非事件选项卡中保持 WebRTC dataChannel 打开?

html - 如何在移动 Web 应用程序中禁用背景 div 上的滚动

html - 如何防止链接显示在 :focus/:active from auto-clicking on a touch screen? 上