#導入正則模塊 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.'