re包含一些模塊級函數,用於處理作爲文本字符串的正則表達式,不過對於程序頻繁使用的表達式,編譯這些表達式會更爲高效。compile()函數會把一個表達式字符串轉換爲一個RegexObject。
- import re
- regexes = [ re.compile(p)
- for p in ['this', 'that']
- ]
- text = 'Does this text match the pattern?'
- print 'Text: %r\n' % text
- for regex in regexes:
- print 'Seeking "%s" ->' % regex.pattern,
- if regex.search(text):
- print 'match!'
- else:
- print 'no match'
輸出:
Text: 'Does this text match the pattern?'
Seeking "this" -> match!
Seeking "that" -> no match
模塊級函數會維護已編譯表達式的一個緩存。不過,這個緩存的大小是有限的,直接使用已編譯表達式可以避免緩存查找開銷。使用已編譯表達式的另一個好處是,通過在加載模塊是預編譯所有表達式,可以把編譯工作轉到應用開始時,而不是當程序響應一個用戶動作是才進行編譯。