>>> A[('576dfCD.HIS', 'CD.'), ('794SDABC@KM', 'ABC')]
贪婪匹配 默认是贪婪匹配, 在括号内加?表示非贪婪匹配 : 贪婪匹配 re.match(r'^(\d+)(0*)$','102300').groups() #('102300', '') 非贪婪匹配 re.match(r'^(\d+?)(0*)$','1022300').groups() #('10223', '00') re.compile()的第二个参数 re.DOTALL 让句点字符匹配所有字符,包括换行符。 noNewlineRegex=re.compile('.*') m='Serve the public trust.\nProtect the innocent.\nUphold the law.' n=noNewlineRegex.search(m).group() print(n) #'Serve the public trust.' newlineRegex=re.compile('.*',re.DOTALL) print(newlineRegex.search(m).group()) ''' Serve the public trust. Protect the innocent. Uphold the law. ''' re.IGNORECASE或re.I 不区分大小写的匹配 robocop=re.compile(r'robocop',re.I) robocop.search('Robocop is part man,part machine,all cop.').group() #'Robocop' re.VERBOSE 忽略正则表达式字符串中的空白符和注释 phoneRegex=re.compile(r'''( (\d{3}|\(\d{3}\))? #area code (\s|-|\.)? #separator \d{3} #first 3 digits (\s|-|\.) #separator \d{4} #last 4 digits (\s*(ext|x|ext.)s*\d{2,5})? #extension )''',re.VERBOSE) 组合使用re.IGNORECASE ,re.DOTALL和re.VERBOSE #如果希望正则表达式不区分大小写,并且句点字符匹配换行,就可以这样构造re.compile()调用: someRegexValue=re.compile('foo',re.IGNORECASE|re.DOTALL) #使用第二个参数的全部3个选项: someRegexValue=re.compile('foo',re.IGNORECASE|re.DOTALL|re.VERBOSE) re.split() 切分字符串 >>> 'a b c'.split(' ') ['a', 'b', '', '', '', 'c'] 固定字符切分字符串,无法识别连续的空格 >>> re.split(r'\s+','a b c') ['a', 'b', 'c'] >>> re.split(r'[\s\,\;]+','a,b ;c d') ['a', 'b', 'c', 'd'] sub() 替换字符串 Regex对象的sub()方法,第一个参数 用于替换 源字符串的 需被 替换 的字符 ,第二个参数是 源字符串 mol=re.compile(r'Agent \w+') mol.sub('CENSORED','Agent Alice gave the secret documents to Agent Bob.') #'CENSORED gave the secret documents to CENSORED.' 保留被替换字符串 中 的一部分内容,在sub()的第一个参数中,可以输入\1、\2、\3.....表示将re 的表达式模式中 的 分组1 ,分组2 ,分组3 的部分显示出来(即不被替换) 假定想要隐去密探的姓名,只显示他们姓名的第一个字母。要做到这一点,可以使用正则表达式Agent(\w)\w*,传入r'\1****'作为sub()的第一个参数。 #字符串中的\1将由分组1匹配的文本所替代,也就是正则表达式的(\w)分组。 agentNamesRegex=re.compile(r'Agent (\w)\w*') agentNamesRegex.sub(r'\1****','Agent Alice told Agent Carol that Agent Eve knew Agent Bob was a double agent.') #'A**** told C**** that E**** knew B**** was a double agent.' #编译 #当我们在python 中使用正则表达式时,re模块内部会干两件事: #1.编译正则表达式,如果正则表达式的字符串本身不合法,会报错 #2.用编译后的正则表达式去匹配字符串。 #如果一个正则表达式要重复使用几千次,出于效率考虑,我们可以预编译该正则表达式,接下来重复使用时就不需要编译这个步骤了,直接匹配
转载于:https://www.cnblogs.com/Ting-light/p/9295787.html