escape.py 829 B

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