[python][正则表达式] re模块核心函数和方法

来源:互联网 发布:pymongo查询大量数据 编辑:程序博客网 时间:2024/06/13 22:20

Python通过re模块支持正则表达式。

本文介绍了re模块核心函数和方法。


  • 在模式匹配发生之前,正则表达式模式必须编译成为正则表达式对象,re模块使用compile()实现;re模块对每个正则表达式模式进行一次编译,然后对编译的对象进行缓存,purge()函数可以清除这些缓存;

  • 使用match()方法,从字符串起始部分开始匹配且仅仅匹配起始部分,如果匹配成功,就返回一个匹配对象,如果失败,就返回None;使用group()可以调用那个成功的匹配;

>>> re.match('\d?','12345').group()'1'>>> re.match('\d+','12345').group()'12345'>>> re.match('\d+','.12345').group()Traceback (most recent call last):  File "<pyshell#20>", line 1, in <module>    re.match('\d+','.12345').group()AttributeError: 'NoneType' object has no attribute 'group'

上面这个栗子中,\d+匹配1个或者多个十进制数字;如果字符串开始不是数字,那么match()方法不能匹配到,则返回None;

  • 使用search方法,从字符串任意部分开始第一次匹配,如果匹配成功,就返回一个匹配对象,如果失败,就返回None;


>>> re.match('\d+','.12345').group()Traceback (most recent call last):  File "<pyshell#27>", line 1, in <module>    re.match('\d+','.12345').group()AttributeError: 'NoneType' object has no attribute 'group'>>> re.search('\d+','.12345').group()'12345'
上面这个栗子中,search可以从任意位置开始匹配,因此可以匹配到不是数字开头的字符串;

  • group()方法和groups()都属于匹配对象方法。group()可以返回整个匹配对象,也可以按照参数给出特定参数的子组;groups()返回整个匹配对象,或者没有匹配时返回None,如果没有子组,则groups()返回空元组;


>>> m=re.match('(\w\w\w)-(\d\d\d)','abc-123')>>> m.group()#完全匹配,有两个子组'abc-123'>>> m.group(1)#第一个子组'abc'>>> m.group(2)#第二个子组'123'>>> m.groups()#全部子组('abc', '123')

>>> m=re.match('\w\w\w-\d\d\d','abc-123')>>> m.group()#完全匹配,没有子组'abc-123'>>> m.group(1)Traceback (most recent call last):  File "<pyshell#37>", line 1, in <module>    m.group(1)IndexError: no such group>>> m.groups()()
上面第二个栗子中,由于没有子组,groups()返回一个空元组。