#导入正则模块 import re #编译正则模式对象 regex = re.compile('string') #使用正则模式匹配字符串,返回字符串中第一次匹配模式的match对象 m = regex.search(stringobject) print m.group()#match对象使用group方法获取匹配文本 #当模式中有()包含时,可使用对应的数值参数精确提取(如 1,2,3等等) #不传参数或0返回整个匹配文本 print m.groups()#一次返回全部分组
re.search(r'batman|spiderman',string) #使用管道符进行多项可能的匹配 re.search(r'Bat(man|mobile|copter)',string)#使用管道符进行多项可能的匹配 re.search(r'Bat(wo)?man',string) # 字符?代表它前面的分组是可选,出现0次或1次 re.search(r'Bat(wo)*man',string) # 字符*代表它前面的分组是可选,出现0次或多(n=1,2...)次 re.search(r'Bat(wo)+man',string) # 字符+代表它前面的分组是必选,出现1次或多(n=2,3...)次 re.search(r'Bat(wo){m,n}man',string) # {}指定前面分组出现的次数,最少m次,最多n次 #Python 的正则表达式默认是“ 贪心” 的, 这表示在有二义的状况下,它们会尽量匹配最长的字符串。 #请注意, 问号在正则表达式中可能有两种含义: 声明非贪心匹配或表示可选的分组。这两种含义是彻底无关的 re.search(r'Bat(wo){m,n}?man',string)#在花括号后方跟上?,变为非贪心模式,匹配符合条件的最短串 #要让正则表达式不区分大小写,能够向 re.compile()传入 re.IGNORECASE 或 re.I,做为第二个参数 regex = re.compile(r'WeRwT',re.I)
默认匹配除换行之外的全部字符,经过传入 re.DOTALL 做为 re.compile()的第二个参数, 可让句点字符匹配全部字符, 包括换行字符。python
noNewlineRegex = re.compile('.*') noNewlineRegex.search('Serve the public trust.\nProtect the innocent\nUphold the law.').group() #'Serve the public trust.' 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.'
有时候,你可能须要使用匹配的文本自己,做为替换的一部分。在 sub()的第一个参数中,能够输入\一、 \二、 \3……,表示“在替换中输入分组 一、 二、 3……的文本”。正则表达式
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. 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.'