python 正则表达式 re模块

来源:互联网 发布:js canvas 画图 编辑:程序博客网 时间:2024/04/20 13:22


#1寻常方式python匹配字符串In [1]: str1='imooc python'In [2]: str1.find('i')Out[2]: 0In [4]: str1.find('z')Out[4]: -1In [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]: paOut[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]:


0 0