Table of Contents
引子
请从以下文件中取出所有的手机号
姓名 地区 身高 体重 电话
况咏蜜 北京 171 48 13651054608
王心颜 上海 169 46 13813234424
马纤羽 深圳 173 50 13744234523
乔亦菲 广州 172 52 15823423525
罗梦竹 北京 175 49 18623423421
刘诺涵 北京 170 48 18623423765
岳妮妮 深圳 177 54 18835324553
贺婉萱 深圳 174 52 18933434452
叶梓萱 上海 171 49 18042432324
杜姗姗 北京 167 49 13324523342
你能想到的办法是什么?
f = open('正则文件.txt', mode='r', encoding='utf8')
phones = []
for line in f:
name, city, height, weight, phone = line.split() # 默认为所有的空字符,包括空格、换行(\n)、制表符(\t)等
if phone.startswith('1') and len(phone)==11:
phones.append(phone)
print(phones)
['13651054608', '13813234424', '13744234523', '15823423525', '18623423421', '18623423765', '18835324553', '18933434452', '18042432324', '13324523342']
import re
f = open('正则文件.txt', mode='r', encoding='utf8')
data = f.read()
print(re.findall('[0-9]{11}', data))
['13651054608', '13813234424', '13744234523', '15823423525', '18623423421', '18623423765', '18835324553', '18933434452', '18042432324', '13324523342']
re模块

常用的表达式规则
‘.’ 默认匹配除\n之外的任意一个字符,若指定flag DOTALL,则匹配任意字符,包括换行
‘^’ 匹配字符开头,若指定flags MULTILINE,这种也可以匹配上(r"^a","\nabc\neee",flags=re.MULTILINE)
"" : 匹 配 字 符 结 尾 , 若 指 定 f l a g s M U L T I L I N E , r e . s e a r c h ( ′ f o o . ": 匹配字符结尾, 若指定flags MULTILINE ,re.search('foo.":匹配字符结尾,若指定flagsMULTILINE,re.search(′foo.’,‘foo1\nfoo2\n’,re.MULTILINE).group() 会匹配到foo1
"" 匹配号前的字符0次或多次, re.search(‘a*’,‘aaaabac’) 结果’aaaa’
‘+’ 匹配前一个字符1次或多次,re.findall(“ab+”,“ab+cd+abb+bba”) 结果[‘ab’, ‘abb’]
‘?’ 匹配前一个字符1次或0次 ,re.search(‘b?’,‘alex’).group() 匹配b 0次
‘{m}’ 匹配前一个字符m次 ,re.search(‘b{3}’,‘alexbbbs’).group() 匹配到’bbb’
‘{n,m}’ 匹配前一个字符n到m次,re.findall(“ab{1,3}”,“abb abc abbcbbb”) 结果’abb’, ‘ab’, ‘abb’]
‘|’ 匹配|左或|右的字符,re.search(“abc|ABC”,“ABCBabcCD”).group() 结果’ABC’
‘(…)’ 分组匹配, re.search("(abc){2}a(123|45)", “abcabca456c”).group() 结果为’abcabca45’
‘\A’ 只从字符开头匹配,re.search("\Aabc",“alexabc”) 是匹配不到的,相当于re.match(‘abc’,“alexabc”) 或^
‘\Z’ 匹配字符结尾,同$
‘\d’ 匹配数字0-9
‘\D’ 匹配非数字
‘\w’ 匹配[A-Za-z0-9]
‘\W’ 匹配非[A-Za-z0-9]
‘s’ 匹配空白字符、\t、\n、\r , re.search("\s+",“ab\tc1\n3”).group() 结果 ‘\t’
\S :非空白
‘(?P…)’ 分组匹配 re.search("(?P[0-9]{4})(?P[0-9]{2})(?P[0-9]{4}
‘[ ]’ :[aoe] [a-w]匹配集合中任意一个字符
分组:
- 贪婪模式:.*
- 非贪婪(惰性)模式:.*?
re.I :忽略大小写
re.M :多行匹配
re.S :单行匹配
re.sub(正则表达式, 替换内容, 字符串)
正则练习
import re
# 提取出 python
key = 'javapythonc++php'
ex = re.findall('python', key)[0]
print(ex)
python
# 提取出 hello world
key = ' \
hello world '
ex = re.findall('\S.*\S', key)[0] # \S:匹配非空白
print(ex)
hello world
# 提取170
string = '他是身高只有170的一名男性'
ex = re.findall('\d+', string)[0]
print(ex)
170
# 提取出https://和htpp://
key = 'http://www.baidu.com and https://boob.com'
ex = re.findall('https?://', key)
print(ex)
['http://', 'https://']
# 提取出 hello
key = 'lalalahellohahahello'
ex = re.findall('[Hh][Ee][Ll][Ll][Oo]', key)
print(ex)
['hello', 'hello']
# 提取出 hit.
key = 'bobo@hit.edu.com'
ex = re.findall('h.*?\.', key)
print(ex)
['hit.']
# 匹配 sas 和 saas
key = 'saas and sas and saaas'
ex = re.findall('sa{1,2}s',key)
print(ex)
['saas', 'sas']