Python RE 模块

re模块

Python对正则表达式的支持,由re这个内置的模块实现。


findall

以列表的形式返回匹配成功的文本。

>>> import re
>>> re.findall('a', 'a') # ['a']
>>> re.findall('a', 'aba') # ['a', 'a']
>>> re.findall('.', 'aba') # ['aba']
>>> re.findall('a{3}', 'aaaa') #['aaa']
>>> re.findall('\d\D', '1aa') # ['1a']
>>> re.findall('^a', 'ba') # []

# 参数(匹配规则,字符)
# 上篇我们介绍的语法,我们可以自己逐个试验,加深理解

match

match匹配成功返回正则对象,失败返回None

>>> r = re.match('a', 'aba')
>>> r
<_sre.SRE_Match object; span=(0, 1), match='a'>

>>> r = re.match('a', 'b')
>>> r is None
True

search

match强制开头匹配,search的功能和match一样,但不强制开头匹配。

>>> r = re.match('a', 'ba')
>>> r is None
True

>>> r = re.search('a', 'ba')
>>> r
<_sre.SRE_Match object; span=(1, 2), match='a'>

>>> r = re.search('^a', 'ba') # ^ 开头匹配 | 这时 match 和 search 就一样了

group

match返回的正则对象提取结果

>>> re.match('a(b)','ab').group() # () 括号是特别的标示,不会影响正则匹配
'ab'

>>> re.match('a(b)','ab').groups() # .groups() 可以只提取用括号标示的内容,这招非常有用!
'b'

sub

替换字符串,这个比 string.replace 方法替换起来好用的地方是:它支持正则表达式的语法,可以做更精准的替换。

>>> re.sub('a|b', 'c', 'abc')
'ccc'

compile

预编译

>>> re.compile('\d')
>>> d.match('1').group()
1
>>> d.match('2').group()
2

# match 每次匹配都要编译一遍,如果一个正则表达式需要多次匹配,使用 compile 都执行效率会高些

对正则表达式的加深理解,可以在网上找些应用的例子,或者参考一下这本书 正则表达式必知必会

更多教程 HTML5 教程 CSS3 教程 JavaScript 教程 JQuery 教程 React.js 教程 Node.js 教程 Koa2 教程 Python 教程 Linux 教程