Python正则模块之RegexObject

一、模块
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)

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值