Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Python re.purge() Method

Python re.purge() Method

Python re Module Python re Module


re.purge() is a function in the Python re module used toClear the regular expression cache.

Python's re module caches compiled regular expression objects to improve performance;re.purge() can clear this cache.

Word meaning: purge means "to purge/clear".


Basic syntax and parameters

Syntax format


re.purge()

Parameter Description

Function description


Example

Example 1: Basic usage

Example

import

re

Use some regular expressions first

re

.

search

(

r

'\d+'

,

'123'

)

re

.

match

(

r

'\w+'

,

'hello'

)

Clear the cache

re

.

purge

(

)

print

(

"Cache cleared"

)

Expected output:

缓存已清除

Example 2: observe the caching effect

Example

import

re

Using the same pattern multiple times - the cache is used

for

_

in

range

(

3

)

:

   

re

.

search

(

r

'\d+'

,

'123'

)

Clear the cache

re

.

purge

(

)

print

(

"Cache cleared; the cache will be rebuilt afterwards"

)

re

.

search

(

r

'\d+'

,

'456'

)

Expected output:

缓存已清除,之后重新创建缓存

Example 3: releasing memory

Example

import

re

import

sys

Create a large number of different regular expressions (which occupy the cache)

patterns

=

[

re

.

compile

(

r

'\d+'

str

(

i

)

)

for

i

in

range

(

100

)

]

print

(

f

"Created {len(patterns)} regular expressions"

)

Clear the cache

re

.

purge

(

)

print

(

"Cache released"

)

Expected output:

创建了 100 个正则表达式
缓存已释放

Usage scenarios


Python re Module Python re Module