一、正则表达式的定义及作用
1.什么叫做正则表达式 :
正则表达式是由字符和特殊字符组成的字符串,用它可以方便的检查一个字符串是否符合某种特定规则。
2.正则表达式的作用:
1.在一段文字中可以搜索特定规则的字符串
2.可以替换特定规则的字符串
3.检验输入的字符串是否符合要求。
二、re模块:核心函数
1.match()和search()
import re
#模式foo匹配字符串 food on the table 合适,输出匹配对象
m = re.match("foo", "food on the table")
#模式匹配字符串失败,返回None
m1 = re.match("foot", "food on the table")
m.group()
m1.group()
输出内容为(第二个返回值为None,运行时会报错)
"foo"
AttributeError: 'NoneType' object has no attribute 'group'
print(m1)#输出值为None
2.group()和groups()
当处理正则表达式时,除了正则表达式对象之外,还有匹配对象即成功调用match()之类 的函数返回的对象。
对象匹配有group()和groups()二种方法。group()返回整个匹配对象或者返回特定子组,groups()返回的是一个包含唯一或者全部子组的元组,如果没有子组的要求,则返回的是一个空组。
import re
s = "bend"
s1 = re.match(".end", s)
s1.groups()
s1.group()
print(s1)
输出结果为
()
'bend'
<_sre.SRE_Match object; span=(0, 4), match='bend'>
3.sub()和subn()
这二个函都有搜索和替换的功能,只不过subn()还返回一个表示替换的总数
re.sub("[ae]", "x", "abcdef")
re.subn("[ae]", "x", "abcdef")
输出结果为
'xbcdxf'
('xbcdxf', 2)
4.findall()和finditer()
与match()和search()不同的是,findall()返回的是一个列表,如果没有找到匹配的部分,就返回一个空列表。
finditer()与findall()功能一样但更节省内存,在匹配对象中迭代,但不是迭代器
s = "this and that"
m = re.findall(r"(th\w+) and (th\w+)", s)
m1 = re.finditer(r"(th\w+)", s,)
m
b = next(m1)
print(b.group(), b.span())#span()表示起始位置
a = next(m1)
print(a.group(), a.span())
输出结果为
[('this', 'that')]
this (0, 4)
that (9, 13)