Python 正则表达式(re模块)

来源:互联网 发布:阿里云腾讯云对比报告 编辑:程序博客网 时间:2024/04/29 22:20

re模块是python的正则表达式模块,下面介绍正则表达式的两种用法:

直接使用表达式

import restrA = "123"a = re.match(r"\d",strA) #字符串前加r可以让字符串中的字符不转意print(a)'''结果:<_sre.SRE_Match object; span=(0, 1), match='1'>'''print(dir(a))#使用dir查看对象属性'''['__class__', '__copy__', '__deepcopy__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__le__', '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'end', 'endpos', 'expand', 'group', 'groupdict', 'groups', 'lastgroup', 'lastindex', 'pos', 're', 'regs', 'span', 'start', 'string']'''#可以使用a.start()获取匹配起始位置#使用a.end()获取匹配结束为止

使用编译后的正则

使用编译后的正则有几点好处:1.编译可以检查正则表达式的正确性,不正确会报错。2可以提高效率。

import ree = re.compile(r"\d")a = e.match("123")#返回的对象和上述例子中的返回值相同类型

子表达式提取例子:

a = re.match(r"(\d)(\d)","123")#使用a.groups()获取匹配的子表达式元组('1', '2')

字符串切割:

re.split(r'\s+','a b         c')#使用正则不论有多少空格都能正确分割,即使中间还有其他的分隔符,只要使用正确的表达式一般都能正确分割#['a', 'b', 'c']
0 0