一、模块
import re
二、RegexObject
(一)模式对象,表现编译后的正则表达式(编译为字节码并缓存)
(二)编译
re.compile(r’模式’)
应用一:
import re
text = ‘Tom is 8 years old.Mike is 25 years old.’
pattern = re.compile(’\d+’)
print(pattern.findall(text))
print(re.findall(’\d+’,text))
应用二:
import re
s = ‘\author:Tom’
pattern =re.compile(’\\author’) #斜杠需要转义,所以需要打4个斜杠
print(pattern.findall(s))
pattern =re.compile(r’\author’) #加r表示是原始的字符串,斜杠不需要转义
print(pattern.findall(s))
(三).findall()
1、查找所有非重叠匹配项
2、返回list
例如:
import re
text = ‘Tom is 8 years old.Mike is 23 years old. Peter is 87 years old.’
pattern = re.compile(r’\d+’)
print(pattern.findall(text))
p_name = re.compile(r’[A-Z]\w+’)
print(p_name.findall(text))
(四).match(string[,pos[,endpos]])
1、匹配仅从起始位置
2、返回一个匹配对象MatchObject
(五).match(string[,pos[,endpos]])
1、任意位置搜索
2、返回一个匹配对象MatchObject
(六).finditer()
1、查找所有匹配项
2、返回包括MatchObject元素的迭代器
例如:
import re
text = ‘Tom is 8 years old.Mike is 35 years old.Peter is 87 years old.’
p1 = re.compile(r’\d+’)
p2 = re.compile(r’[A-Z]\w+’)
print(p1.match(text)) #返回None,因为并不是以数字开头
print(p2.match(text))
print(p1.search(text))
it = p1.finditer(text)
for m in it:
print(m)
Python正则模块之RegexObject
最新推荐文章于 2021-09-07 10:57:22 发布