天天看點

Python正規表達式

一.執行個體

import re
NameRe = re.compile(r'\d{3}-\d{3}-\d{4}') #建立比對對象,r為原始字元
name = NameRe.search("asdasdsadasd") #比對失敗傳回None,成功傳回Match對象,就一個
print(name.group()) #傳回比對到的内容

#直接過濾
result = re.match('You', 'Young Frankenstein')
youpattern = re.compile('You')
result = youpattern.match('Young Frankenstein')


NameRe = re.compile(r'(\d{3})-(\d{3}-\d{4})') #分組
print(name.group(1)) #1傳回1組,0和不寫,傳回所有比對到的
a,b = mo.groups() #分别獲得變量

name = NameRe.findall('asdasdas') #傳回所有比對結果,清單套元組

re.complir(r'abc|bcd') #比對其中一個,傳回第一次比對到的值
re.compile(r'Bat(man|mobile|copter|bat)') #Bat可以複寫
re.compile(r'Bat(wo)?man') #wo可有可無,比對問好前的分組0次或1次
re.compile(r'Bat(wo)*man') #比對之前的分組0次或無數次
re.compile(r'Bat(wo)+man') #之前的分組1次或多次
re.compile(r'Bat(wo){3}') #之前的分組3次
re.compile(r'Bat(wo){1,3}') #之前的分組1次或3次
re.compile(r'Bat(wo){3,5}?') #在分組的時候,實作非貪心比對,進來比對最短
re.compile(r'Bat[0-5]') #0-5之前
re.compile(r'[a-zA-Z0-9]') #比對所有字母和數字
re.compile(r'Bat[^0-5]') #取反
re.compile(r'^Bat&') #開始到結束都是Dat的
re.compile(r'.Bat') #除了換行之外的所有字元
re.compile(r'.Bat(.*)') #比對所有字元串
re.compile(r'.Bat(.*)?') #比對所有字元串,非貪婪比對,盡量少比對
re.compile('.*', re.DOTALL) #比對所有,包括有換行等等
re.compile(r'robocop', re.I) #不區分大小寫比對
name.sub(字元,字元) #前一個是替換後的,後一個是要比對替換的字元串
name.sub(r'\1****', 'Agentasdasd') #将第一組替換為* \2第二組
re.compile(r'''asda
asdasd
asdad''', re.VERBOSE) #多行正則,可寫注釋
re.compile('foo', re.IGNORECASE | re.DOTALL) #多參數調用
           

二.規則

Python正規表達式
Python正規表達式

三.具體例子

#比對電話号碼
phoneRegex = re.compile(r'''(
    (\d{3}|\(\d{3}\))?  #3個數字或括号中的3個數字
    (\s|-|\.)?  #空白或-或.
    (\d{3}) #3個數字
    (\s|-|\.)  #空白或-或.
    (\d{4})  #4個數字
    (\s*(ext|x|ext.)\s*(\d{2,5}))? #任意數量空白+可選ext+任意數量空白+2-5個數字
    )''', re.VERBOSE)
           
#比對郵件位址
emailRegex = re.compile(r'''(
    [a-zA-Z0-9._%+-]+ #一個或多個字元,字母數字下劃線,百分号,加好,短橫,句号
    @   #@符
    [a-zA-Z0-9.-]+ #同上比對
    (\.[a-zA-Z]{2,4}) #.com這種域名部分,重複2-4個
    )''', re.VERBOSE)
           
from collections import namedtuple
Duck = namedtuple('Duck', 'bill tail')
duck = Duck('wide irange', 'log')
duck
duck.bill

parts = {'bill': 'wide orange', 'tail': 'long'} #字典構造命名元祖
duck2 = Duck(**parts)

duck3 = duck2._replace(tail='magnificent', bill='crushing') #替換部分值,傳回新的



search() 會傳回第一次成功比對,如果存在的話
m = re.search('Frank', 'Young Frankenstein')

findall() 會傳回所有不重疊的比對的清單,如果存在的話
m = re.findall('n', 'Young Frankenstein')

split() 會根據 pattern 将 source 切分成若幹段,傳回由這些片段組成的清單;
m = re.split('n', source) #以n分隔,将其它字元放到數組

sub() 還需一個額外的參數 replacement,它會把 source 中所有比對的 pattern 改成replacement。
m = re.sub('n', '?', source) #傳回字元串,将比對到的n換成問号


#字元串常量
import string
printable = string.printable
print(printable)

re.findall('\d', printable) #找出數字
re.findall('\w', printable) #數字,字元,下劃線
re.findall('\s', printable) #哪些是空格
re.findall('[wf]ish', source) #w或f開頭
re.findall('[wsh]+', source) #若幹個w、s、h的組合
re.findall('I (?=wish)', source) #I開頭,後面跟wish,出現次數盡量少
re.findall('(?<=I) wish', source) #查詢以wish結尾,前面為I的比對(I出現的次數盡量少)

           

本文版權歸作者所有,歡迎轉載,請務必添加原文連結。