python 正则表达式 re模块


#1寻常方式python匹配字符串
In [1]: str1='imooc python'
In [2]: str1.find('i')
Out[2]: 0
In [4]: str1.find('z')
Out[4]: -1
In [6]: str1.startswith('i')
Out[6]: True
#2.正则表达式re的使用
import re
#匹配'imooc',re的compile方法生成一个pattern对象
pa=re.compile(r'imooc')
#调用pattern的方法match匹配字符串
#匹配的结果放在math的对象里面,用match的方法显示匹配的结果
ma=pa.match(str1)#返回math对象
ma.group()#匹配字符串的数据
ma.span()#匹配的数据区间
ma.groups()#匹配的元组


In [11]: pa=re.compile(r'Imooc python',re.I)
In [12]: pa
Out[12]: re.compile(r'Imooc python', re.IGNORECASE)#忽略大小写




In [22]: pa=re.compile(r'(imooc)',re.I)

In [23]: ma=pa.match(str1)

In [24]: print ma.groups()#返回一个元组
('imooc',)


In [30]: ma1=re.match(r'imooc','imooc python')#简便写法

In [31]: ma1.group()
Out[31]: 'imooc'

In [32]: ma1=re.match(r'imooc','Z')

In [33]: ma1.group()
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-33-a04cfb428c99> in <module>()
----> 1 ma1.group()

AttributeError: 'NoneType' object has no attribute 'group'

In [34]:











评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值