分析
目前常见的电话号码有:手机号码,座机号码,400开头的电话
手机号码
手机号码为11位,第一位一定是1,后面跟着10位号码;
例如:188xxxx6542,157xxxx5231等等。
座机号码
座机号码是由两部分组成:区号+座机号;
区号有3-4位数;
座机号有7-8位数;
例如:010-87655210,028-83387337,0371-6515835
400
400电话为10位号码组成;
例如:400-700-5606
匹配的字符串
content = """
<form id="loginform" οnsubmit="return QMLogin.checkInput();" method="post" name="loginform"target="_self" autocomplete="on" ><div class="login_submit" style=""><input class="login_button" id="btlogin" name="btlogin" type="submit" value="登录" tabindex="5" /></div></form>
<a href="114.aspx?w=小米">小米</a><span> | </span>
<a href="114.aspx?w=010-87655210">010-87655210</a><span> | </span>
<a href="114.aspx?w=快递">快递</a><span> | </span>
<a href="114.aspx?w=18210443800">18210443800</a><span> | </span>
<a href="114.aspx?w=深圳">深圳</a><span> | </span>
<a href="tel:400-606-0201" class="text-link-tertiary hover:text-link-tertiary-hover hover:underline active:text-link-tertia
"""
正则表达式
手机号码
正则匹配前后限制非数字,防止随意匹配一长段数字中的部分号码
re_phone = '[^0-9](1[3-9][0-9]{9})[^0-9]'
phone_number_lt = list(set(re.findall(re_phone, content)))
phone_number_lt = [e for e in phone_number_lt if e != '']
座机号码
正则匹配前后限制非数字,防止随意匹配一长段数字中的部分号码
re_phone = '[^0-9](0[0-9]{2,3}\-[2-9][0-9]{6,7})[^0-9]'
phone_number_lt = list(set(re.findall(re_phone, content)))
phone_number_lt = [e for e in phone_number_lt if e != '']
400
正则匹配前后限制非数字,防止随意匹配一长段数字中的部分号码
re_phone = '[^0-9](400-[0-9]{3}-[0-9]{4})[^0-9]'
phone_number_lt = list(set(re.findall(re_phone, content)))
phone_number_lt = [e for e in phone_number_lt if e != '']
总结
将上述三个正则表达式整合到一块
re_phone = '[^0-9](0[0-9]{2,3}\-[2-9][0-9]{6,7}|1[3-9][0-9]{9}|400-[0-9]{3}-[0-9]{4})[^0-9]'
phone_number_lt = list(set(re.findall(re_phone, content)))
phone_number_lt = [e for e in phone_number_lt if e != '']