py3: make mreplace polyglot

This commit is contained in:
Kovid Goyal 2019-05-20 13:40:20 +05:30
parent 749885778d
commit 3e64b73c96
No known key found for this signature in database
GPG Key ID: 06BC317B515ACE7C

View File

@ -1,4 +1,5 @@
# multiple replace from dictionnary : http://code.activestate.com/recipes/81330/ # multiple replace from dictionnary : http://code.activestate.com/recipes/81330/
from __future__ import unicode_literals
__license__ = 'GPL v3' __license__ = 'GPL v3'
__copyright__ = '2010, sengian <sengian1 @ gmail.com>' __copyright__ = '2010, sengian <sengian1 @ gmail.com>'
__docformat__ = 'restructuredtext en' __docformat__ = 'restructuredtext en'
@ -22,7 +23,10 @@ class MReplace(UserDict):
def compile_regex(self): def compile_regex(self):
if len(self.data) > 0: if len(self.data) > 0:
keys = sorted(self.data, key=len, reverse=True) keys = sorted(self.data, key=len, reverse=True)
tmp = "(%s)" % "|".join(map(re.escape, keys)) if isinstance(keys[0], bytes):
tmp = b"(%s)" % b"|".join(map(re.escape, keys))
else:
tmp = "(%s)" % "|".join(map(re.escape, keys))
if self.re != tmp: if self.re != tmp:
self.re = tmp self.re = tmp
if self.case_sensitive: if self.case_sensitive: