[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()返回一个空元组。
阅读全文
0 0
- [python][正则表达式] re模块核心函数和方法
- [Python]re模块的核心函数和方法
- 正则表达式和python的re模块
- 正则表达式,和python re模块
- Python正则表达式和re模块
- Python中的re模块和正则表达式
- 正则表达式和python re模块
- python正则表达式和re模块
- python正则表达式:re模块
- Python 正则表达式 re模块
- Python 正则表达式,re模块
- Python re模块正则表达式
- Python正则表达式re模块
- Python正则表达式,re模块
- python 正则表达式 re模块
- Python 正则表达式 re模块
- python---re模块,正则表达式
- python正则表达式模块re
- centos7下安装mycat
- oracle函数listagg的使用说明
- 雷军20年前代码
- linux crypt()函数使用总结
- 编译安卓Linux内核并替换(配置支持LKM) (MD)
- [python][正则表达式] re模块核心函数和方法
- java中的一些数据格式的声明、使用(一)
- layer icon图标汇总
- 发送Ajax请求
- codeforces [Gym-100814E]
- Lua 为什么在游戏编程领域被广泛运用?
- 多校5 HDU-6095 Rikka with Competition
- 框架嵌套事务
- 为树莓派打造一个安全关机的功能,不需要命令行,不需要额外电路板!