1. 程式人生 > >python 中的 re.compile 函式

python 中的 re.compile 函式

1. 使用re.compile

re模組中包含一個重要函式是compile(pattern [, flags]) ,該函式根據包含的正則表示式的字串建立模式物件。可以實現更有效率的匹配。在直接使用字串表示的正則表示式進行search,match和findall操作時,python會將字串轉換為正則表示式物件。而使用compile完成一次轉換之後,在每次使用模式的時候就不用重複轉換。當然,使用re.compile()函式進行轉換後,re.search(pattern, string)的呼叫方式就轉換為 pattern.search(string)的呼叫方式。

其中,後一種呼叫方式中,pattern是用compile建立的模式物件。如下:

>>> import re
>>> some_text = 'a,b,,,,c d'
>>> reObj = re.compile('[, ]+')
>>> reObj.split(some_text)
['a', 'b', 'c', 'd']

 

2.不使用re.compile

在進行search,match等操作前不適用compile函式,會導致重複使用模式時,需要對模式進行重複的轉換。降低匹配速度。而此種方法的呼叫方式,更為直觀。如下:

>>> import re
>>> some_text = 'a,b,,,,c d'
>>> re.split('[, ]+',some_text)
['a', 'b', 'c', 'd']