正则表达式
Talk is cheap. Show me the code.
import re
#注:介绍方法过后,==>是对参数的解释
#re: 查找母串是否含某子串,母串中提取子串,匹配的子串进行替换操作
'''正则表达式:一种特殊规则的字符串,特殊之处在二:一是,它是按照某种规则进行的
,可能不只有一个值。二是,它有对应的方法,match。换句话说,正则表达式就是一个用于匹配字符串的模板'''
'''上面这种预编译用到正则表达式对象,更加强大。'''
print('第零部分:这只是个示例')
#预编译正则表达式(预编译的好处是,可以多次调用)
#re.compile('string') ==>子串
#p是.pattern对象的实例,是一个缓存
p = re.compile('abc')
#调用这个实例的方法search('string')==>母串
a = p.search('www.abc.com')
print(a)#可以看到 <_sre.SRE_Match object; span=(4, 7), match='abc'>
#span()返回匹配的位置,group()返回匹配的组 如下两行:
print(a.span())
print(a.group())
#不使用预编译的话,上面也可以这样写
a = re.search('abc','www.abc.com')
print('\n第一部分:只返回一处 match 和 search ')
#re.match(pattern,string,flags=0) ==>正则,母串,旗标
#match:从开始位置匹配,不成功返回none,成功则返回一个Match对象
m1 = re.match('www','www.fkit.org')
print(m1)
print(m1.span())
print(m1.group())
#re.search(pattern,string,flags=0) ==>正则,母串,旗标
#search:扫描整个,不成功返回none,成功返回match对象
m2 = re.search('fkit','www.fkit.org')
print(m2)
print(m2.span())
print(m2.group())
print('\n第二部分:返回多处 findall 和 finditer ')
#re.findall(pattern,string,flags=0) ==>正则,母串,旗标
#findall:扫描整个,返回所有匹配正则的子串的列表
m3 = re.findall('hello','hello world,hello python')
print(m3)
#re.finditer(pattern,string,flags=0) ==>正则,母串,旗标
#finditer:扫描整个,返回所有匹配正则的子串的迭代器
m4 = re.finditer('hello','hello world,hello python')
for m4_ in m4:
print(m4_)#会打印两个match对象
print('\n第三部分:全匹配与替换 fullmatch 和 sub ')
#re.fullmatch(pattern,string,flags=0) ==>正则,母串,旗标
#fullmatch:扫描整个,要求母串等于子串,不等返回none,等于返回match
m5 = re.fullmatch('hello','hello world,hello python')
print(m5)
#re.sub(pattern,repl,string,count=0,flags=0)
# ==>正则,用于替换的,母串,替换次数(为零则全换),旗标
#sub:扫描整个,要求母串等于子串,不等返回none,等于返回match
m6 = re