escape.py 790 B

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. # Copyright (c) 2010-2024 openpyxl
  2. """
  3. OOXML has non-standard escaping for characters < \031
  4. """
  5. import re
  6. def escape(value):
  7. r"""
  8. Convert ASCII < 31 to OOXML: \n == _x + hex(ord(\n)) + _
  9. """
  10. CHAR_REGEX = re.compile(r"[\001-\031]")
  11. def _sub(match):
  12. """
  13. Callback to escape chars
  14. """
  15. return "_x{:0>4x}_".format(ord(match.group(0)))
  16. return CHAR_REGEX.sub(_sub, value)
  17. def unescape(value):
  18. r"""
  19. Convert escaped strings to ASCIII: _x000a_ == \n
  20. """
  21. ESCAPED_REGEX = re.compile("_x([0-9A-Fa-f]{4})_")
  22. def _sub(match):
  23. """
  24. Callback to unescape chars
  25. """
  26. return chr(int(match.group(1), 16))
  27. if "_x" in value:
  28. value = ESCAPED_REGEX.sub(_sub, value)
  29. return value