Python 正则表达式(re模块)
2017-02-27 17:18
435 查看
re模块是python的正则表达式模块,下面介绍正则表达式的两种用法:
子表达式提取例子:
字符串切割:
直接使用表达式
import re strA = "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 re e = 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']
相关文章推荐
- Python正则表达式与re模块
- Python正则表达式模块(re)简介
- python中正则表达式与re 模块
- Python学习笔记6-Python中re(正则表达式)模块学习
- python之re模块,正则表达式
- Python中re(正则表达式)模块学习
- Python 正则表达式 re 模块简明笔记
- Python 正则表达式 RE模块的使用方法
- python re 模块及正则表达式调用认识 (2)
- python学习笔记正则表达式re模块
- Python中re(正则表达式)模块函数学习
- Python的re模块正则表达式操作
- Python中re(正则表达式)模块学习
- Python笔记(8)re模块,正则表达式
- Python模块学习 ---- re 正则表达式
- python模块之re正则表达式详解
- Python 正则表达式_re模块_使用compile加速
- PYTHON--re模块与正则表达式
- python模块之re正则表达式
- Python中re(正则表达式)模块学习