1、正则表达式匹配步骤
1)用import re导入正则表达式模块
2)用re.compile()创建一个Regex对象
3)向Regex对象的search方法传入要查找的字符串,返回一个Match对象
4)调用Match对象的group方法,返回实际匹配文本的字符串
2、常用匹配符
():正则表达式分组
|:管道字符
?:可选字符
*:匹配0次或多次
+:匹配1次或多次
{}:匹配特定次数,如{3,5}表示贪心匹配3到5次,最多5次; {3,5}?表示非贪心匹配,只匹配3个
花括号后+问号:{}? 非贪心匹配
\d:0-9的任何数字
\D:除0-9的数字外的任何字符
\w:任何字母、数字、下划线(可匹配单词)
\W:除字母、数字、下划线外的任何字符
\s:空格、制表符、换行符(可匹配空白字符)
\S:除空格、制表符、换行符外的任何字符
^:从字符串开始位置匹配
$:字符串必须以$前的字符模式结束
import re
beginsWithHello=re.compile(r'^Hello')
beginsWithHello.search('Hello world!')
endsWithNumber=re.compiler(r'\d$')
endsWithNumber.search('Your number is 42')
匹配都是数字的字符串:r'^\d+$'
wholeStringIsNum=re.compile(r'^\d+$')
wholeStringIsNum.search('1234567890')
3、常用方法
search():返回Match对象,包含被查找字符串的第一次匹配文本
findall():返回一组字符串,包含被查找字符串的所有匹配
group():返回匹配的字符串内容
groups():一次获取所有分组
4、通配符
.(句点):除了换行之外的所有字符
.*(点星):贪心匹配,表示除换行外的所有字符串,传入参数re.DOTALL作为第二个参数,可以匹配所有字符,包括换行字符
.*?(点星问):非贪心匹配,表示尽可能多文本
nongreedyRegex=re.compile(r'<.*?>')
mo=nongreedyRegex.search('<To serve man> for dinner .>')
mo.group()
打印: <To serve man>
greedyRegex=re.compile(r'<.*>')
mo=greedyRegex.search('<To serve man> for dinner .>')
mo.group()
打印: <To serve man> for dinner .>
newlineRegex=re.compile('.*',re.DOTALL)
newlineRegex.search('Serve the public trust.\nProtect the innocent.\nUphold the law.').group()
打印: Serve the public trust.\nProtect the innocent\nUphold the law.
5、re.compile()传入re.I,做为第二个参数,不区分大小写
robocop=re.compile(r'robocop',re.I)
robocop.search('Robocop is part man,part machine,all cop.').group()
打印:Robocop
6、替换字符串sub()
namesRegex=re.compile(r'Agent \w+')
namesRegex.sub('CENSORED','Agent Alice gave the secret documents to Agent Bob.')
打印: CENSORED gave the secret documents to CENSORED
7、忽略空白符和注释 re.VERBOSE
phoneRegex=re.compile(r'''(
(\d{3}|\(\d{3}\))? #area code
(\s|-|\.)? #separator
\d{3} #first 3 digits
)''',re.VERBOSE)
8、组合使用re.IGNORECASE、re.DOTALL、re.VERBOSE
someRegexValue=re.compile('foo',re.IGNORECASE|re.DOTALL|re.VERBOSE)