以下介紹在python的re模塊中怎樣應(yīng)用正則表達(dá)式
1. 使用re.compile
re模塊中包含一個(gè)重要函數(shù)是compile(pattern [, flags]) ,該函數(shù)根據(jù)包含的正則表達(dá)式的字符串創(chuàng)建模式對(duì)象??梢詫?shí)現(xiàn)更有效率的匹配。在直接使用字符串表示的正則表達(dá)式進(jìn)行search,match和findall操作時(shí),python會(huì)將字符串轉(zhuǎn)換為正則表達(dá)式對(duì)象。而使用compile完成一次轉(zhuǎn)換之后,在每次使用模式的時(shí)候就不用重復(fù)轉(zhuǎn)換。當(dāng)然,使用re.compile()函數(shù)進(jìn)行轉(zhuǎn)換后,re.search(pattern, string)的調(diào)用方式就轉(zhuǎn)換為 pattern.search(string)的調(diào)用方式。
其中,后一種調(diào)用方式中,pattern是用compile創(chuàng)建的模式對(duì)象。如下:
>>> import re
>>> some_text = 'a,b,,,,c d'
>>> reObj = re.compile('[, ]+')
>>> reObj.split(some_text)
['a', 'b', 'c', 'd']
2.不使用re.compile
在進(jìn)行search,match等操作前不適用compile函數(shù),會(huì)導(dǎo)致重復(fù)使用模式時(shí),需要對(duì)模式進(jìn)行重復(fù)的轉(zhuǎn)換。降低匹配速度。而此種方法的調(diào)用方式,更為直觀。如下:
>>> import re
>>> some_text = 'a,b,,,,c d'
>>> re.split('[, ]+',some_text)
['a', 'b', 'c', 'd']