Python re.purge() Method
re.purge()is a Pythonremodule function used toclear regular expression cachefunction.
Python's re module caches compiled regular expression objects to improve performance,re.purge()can clear this cache.
Word Definition: purgemeans to clear, purge.
Basic Syntax and Parameters
Syntax Format
re.purge()
Parameter Description
- No parameters
Function Description
- Return Value: No return value.
- Function: Clears all compiled regular expressions cached internally by the re module.
Examples
Example 1: Basic Usage
Example
import re
# First use some regular expressions
re.search(r'\d+', '123')
re.match(r'\w+', 'hello')
# Clear the cache
re.purge()
print("Cache cleared")
# First use some regular expressions
re.search(r'\d+', '123')
re.match(r'\w+', 'hello')
# Clear the cache
re.purge()
print("Cache cleared")
Expected output:
Cache cleared
Example 2: Viewing Cache Effect
Example
import re
# Use the same pattern multiple times - cache will be used
for _ in range(3):
re.search(r'\d+', '123')
# Clear the cache
re.purge()
print("Cache cleared, it will be recreated afterwards")
re.search(r'\d+', '456')
# Use the same pattern multiple times - cache will be used
for _ in range(3):
re.search(r'\d+', '123')
# Clear the cache
re.purge()
print("Cache cleared, it will be recreated afterwards")
re.search(r'\d+', '456')
Expected output:
Cache cleared, and will be recreated afterwards
Example 3: Memory Release
Example
import re
import sys
# Create a large number of different regular expressions (will occupy 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")
import sys
# Create a large number of different regular expressions (will occupy 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 Scenario Description
- Use when memory needs to be released
- Use when regular expressions need to be reloaded after modification
- Periodically clean the cache in long-running programs
Other Extensions