2020年9月3日 / 4,072次阅读 / Last Modified 2020年9月3日
re模块
re.compile函数可以对一个正则表达式进行编译,生成一个compiled re object,然后再用这个object来做匹配的工作。先单独编译,再做匹配,如果匹配这个动作是反复循环做的,可以提高代码运行效率。
>>> import re
>>>
>>> ore = re.compile(r'\d{4}')
>>> a = ['1234','abc123','123bgt4567','qwer1234']
>>> for it in a:
... if ore.search(it):
... print(it)
...
1234
123bgt4567
qwer1234
这段代码用预先编译好的ore正则表达式对象,在一个循环中匹配含有4个数字的字符串,匹配成功就将其打印出来。
正则表达式re模块中常用的匹配函数(match,search,findall,sub...),编译后的对象都有,仅仅是少了一个参数:
>>> >>> for it in dir(ore):
... print(it)
...
__class__
__copy__
__deepcopy__
__delattr__
__dir__
__doc__
__eq__
__format__
__ge__
__getattribute__
__gt__
__hash__
__init__
__init_subclass__
__le__
__lt__
__ne__
__new__
__reduce__
__reduce_ex__
__repr__
__setattr__
__sizeof__
__str__
__subclasshook__
findall
finditer
flags
fullmatch
groupindex
groups
match
pattern
scanner
search
split
sub
subn
-- EOF --
本文链接:https://www.pynote.net/archives/2442
前一篇:用pydoc查看导出docstring
后一篇:用或不用pow函数?
©Copyright 麦新杰 Since 2019 Python笔记