Python re.purge() Method
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
- No parameters
Function description
- Return Value: No return value.
- Purpose: Clears all compiled regular expressions cached inside the re module.
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
(
)
(
"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
(
)
(
"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
)
]
(
f
"Created {len(patterns)} regular expressions"
)
Clear the cache
re
.
purge
(
)
(
"Cache released"
)
Expected output:
创建了 100 个正则表达式
缓存已释放
Usage scenarios
- Use it when you need to release memory
- Use it when a regular expression has been modified and needs to be reloaded
- Periodically clear the cache in long-running programs
Python re Module