# 【问题解答】Python提取一个或多个电话号码

Python 4462浏览

Q：

python同一行 获取不同数据怎么写?正则-CSDN问答

python

```PRINTABLE:张三TEL;VOICE:13882200000TEL:+8618674060000
PRINTABLE:王二TEL;VOICE:13987200000
PRINTABLE:李四TEL;VOICE:13987200000TEL:+861549860000TEL:18674060000```

A：

• 先把要匹配的内容，电话号码，出现的规律，用语言组织和表达出来

• 再去把规律，转换成正则

（1）先把要匹配的内容，电话号码，出现的规律，用语言组织和表达出来

```每一行中

有的是VOICE:
有的是TEL:

内容的规律
有的是1xx开头的，比如 13987200000
有的是+86再加1xx开头的，比如 +861549860000
长度的规律
1xx部分，是固定的11位
如果有+86，则是 3+11=14位```

（2）再去把规律，转换成正则

`#!/usr/bin/python`

# -*- coding: utf-8 -*-

# Author: Crifan Li

# Update: 20191216

# Function: Using regex to extract phone numbers

import re

def reExtractPhone():

print(“=”*60)

# Method 1: single input mutiple line str

multipleLinePhoneStr = “””PRINTABLE:张三TEL;VOICE:13882200000TEL:+8618674060000

PRINTABLE:王二TEL;VOICE:13987200000

PRINTABLE:李四TEL;VOICE:13987200000TEL:+8615498601234TEL:18674060000″””

# phoneRule = “((\+86)?\d{11})”

phoneRule = “((VOICE:)|(TEL:))((\+86)?\d{11})”

matchPhoneList = re.findall(phoneRule, multipleLinePhoneStr, re.MULTILINE)

# print(“matchPhoneList=%s” % matchPhoneList)

print(“multipleLinePhoneStr=%s =>” % multipleLinePhoneStr)

if matchPhoneList:

for curIdx, eachMatchPhone in enumerate(matchPhoneList):

# print(“eachMatchPhone=%s” % (eachMatchPhone, ))

singlePhone = eachMatchPhone[3]

print(“[%d] singlePhone=%s” % (curIdx, singlePhone))

# [0] singlePhone=13882200000

# [1] singlePhone=+8618674060000

# [2] singlePhone=13987200000

# [3] singlePhone=13987200000

# [4] singlePhone=+8615498601234

# [5] singlePhone=18674060000

print(“=”*60)

# Method 2: mutiple input single line str

inputPhoneStrList = [

“PRINTABLE:张三TEL;VOICE:13882200000TEL:+8618674060000”,

“PRINTABLE:王二TEL;VOICE:13987200000”,

“PRINTABLE:李四TEL;VOICE:13987200000TEL:+8615498601234TEL:18674060000”,

]

for curIdx, eachInputPhoneStr in enumerate(inputPhoneStrList):

phoneRule = “((VOICE:)|(TEL:))((\+86)?\d{11})+”

matchPhoneList = re.findall(phoneRule, eachInputPhoneStr, re.DOTALL)

# print(“matchPhoneList=%s” % matchPhoneList)

print(“[%d] eachInputPhoneStr=%s =>” % (curIdx, eachInputPhoneStr))

for eachMatchPhone in matchPhoneList:

# print(“eachMatchPhone=%s” % (eachMatchPhone, ))

singlePhone = eachMatchPhone[3]

print(“singlePhone=%s” % singlePhone)

# [0] eachInputPhoneStr=PRINTABLE:张三TEL;VOICE:13882200000TEL:+8618674060000 =>

# singlePhone=13882200000

# singlePhone=+8618674060000

# [1] eachInputPhoneStr=PRINTABLE:王二TEL;VOICE:13987200000 =>

# singlePhone=13987200000

# [2] eachInputPhoneStr=PRINTABLE:李四TEL;VOICE:13987200000TEL:+8615498601234TEL:18674060000 =>

# singlePhone=13987200000

# singlePhone=+8615498601234

# singlePhone=18674060000

if __name__ == “__main__”:

reExtractPhone()

`\d{11}`

`\d{10,11}`

【后记】

RegExr: Learn, Build, & Test RegEx

82 queries in 0.161 seconds, using 22.10MB memory