regex_compare.py 1.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  1. # coding=utf-8
  2. """
  3. @project: maxkb
  4. @Author:wangliang181230
  5. @file: regex_compare.py
  6. @date:2026/3/30 12:11
  7. @desc:
  8. """
  9. import re
  10. from typing import List
  11. from application.flow.compare import Compare
  12. from common.cache.mem_cache import MemCache
  13. match_cache = MemCache('regex', {
  14. 'TIMEOUT': 3600, # 缓存有效期为 1 小时
  15. 'OPTIONS': {
  16. 'MAX_ENTRIES': 500, # 最多缓存 500 个条目
  17. 'CULL_FREQUENCY': 10, # 达到上限时,删除约 1/10 的缓存
  18. },
  19. })
  20. def compile_and_cache(regex):
  21. match = match_cache.get(regex)
  22. if not match:
  23. match = re.compile(regex).match
  24. match_cache.set(regex, match)
  25. return match
  26. class RegexCompare(Compare):
  27. def support(self, node_id, fields: List[str], source_value, compare, target_value):
  28. if compare == 'regex':
  29. return True
  30. def compare(self, source_value, compare, target_value):
  31. match = compile_and_cache(str(target_value))
  32. return bool(match(str(source_value)))