肉渣教程

正则匹配

上一节 下一节

关于使用python的re模块进行正则匹配,这里初步了解即可;等真正有绝对需求时,再深入研究学习也不迟。


re模块 - 正则匹配

Python内置的re模块是用来进行正则匹配的。如下所示,findall方法是用来找到所有符合正则表达式的子串,sub是用来根据指定正则表达式进行替换,示例如下:

>>> import re
>>> re.findall(r'\bz[a-z]*', 'zombies in the zoo like zhuanfou.')
['zombies', 'zoo', 'zhuanfou']
>>> re.sub(r'(\b[a-z]+) \1', r'\1', 'zombies in in the zoo')
'zombies in the zoo'


相对来说,正则表达式比较晦涩难懂,如果不是一定要进行正则匹配,那就使用字符串类型的内置方法即可,比如replace方法。

>>> 'zombies on the sky'.replace( 'zombies', 'birds' )
'birds on the sky'

正则匹配

上一节 下一节