正则表达式
创建
Python 中所有正则表达式的函数都在 re 模块中。
>>> import re
>>> phoneNumRegex = re.compile(r'\d\d\d-\d\d\d-\d\d\d\d')
info
在字符串的第一个引号之前带有一个前导 r 字符,称为原始字符串;只要是定义正则表达式,就请使用原始字符串。
匹配 Regex 对象
search
Regex 对象的 search() 方法查找传入的字符串,以寻找该正则表达式的所有匹配。
>>> phoneNumRegex = re.compile(r'\d\d\d-\d\d\d-\d\d\d\d')
>>> mo = phoneNumRegex.search('My number is 415-555-4242.')
>>> print('Phone number found: ' + mo.group())
Phone number found: 415-555-4242
info
如果 字符串中没有找到该正则表达式模式,那么 search() 方法将返回 None。如果找到了该模式,search() 方法将返回一个 Match 对象,包含被查找字符串中的 “第一次” 匹配的文本。 Match 对象有一个 group() 方法,它返回被查找字符串中实际匹配的文本。
findall
findall() 方法将返回一组字符串,包含被查找字符串中的“所有”匹配文本。
>>> phoneNumRegex = re.compile(r'\d\d\d-\d\d\d-\d\d\d\d') # has no groups
>>> phoneNumRegex.findall('Cell: 415-555-9999 Work: 212-555-0000')
['415-555-9999', '212-555-0000']
替换文本
除了能从文本中提取字符串,Python 的正则表达式模块还可以在文本中查找字符串并用其他字符串进行原地替换。只要用正则替换方法 sub 就可以完成这一任务。
>>> import re
>>> string = "If the the problem is textual, use the the re module"
>>> pattern = r"the the"
>>> regexp = re.compile(pattern)
>>> regexp.sub("the", string)
'If the problem is textual, use the re module'