逆转Python的re.escape

Wil*_*lem 5 python regex escaping python-3.x

如何反向重新逃生?这个2007年的博客说没有反向功能,但是十年后仍然如此吗?

Python 2 decode('string_escape')不适用于所有转义的字符(例如空格)。

>>> re.escape(' ')
'\\ '
>>> re.escape(' ').decode('string-escape')
'\\ '
Run Code Online (Sandbox Code Playgroud)

Python的3:有些人建议 unicode_escapecodec.escape_decodeast.literal_eval但空间没有运气。

>>> re.escape(b' ')
b'\\ '
>>> re.escape(b' ').decode('unicode_escape')
'\\ '
>>> codecs.escape_decode(re.escape(b' '))
(b'\\ ', 2)
>>> ast.literal_eval(re.escape(b' '))
ValueError: malformed node or string: b'\\ '
Run Code Online (Sandbox Code Playgroud)

那么这真的是唯一有效的方法吗?

>>> re.sub(r'\\(.)', r'\1', re.escape(' '))
' '
Run Code Online (Sandbox Code Playgroud)

Zer*_*eus 5

那么这真的是唯一有效的方法吗?

>>> re.sub(r'\\(.)', r'\1', re.escape(' '))
' '
Run Code Online (Sandbox Code Playgroud)

是的。re模块中没有unescape()的功能,所以你肯定会拥有一个自己写。

此外,该re.escape()功能使用str.translate()

def escape(pattern):
    """
    Escape special characters in a string.
    """
    if isinstance(pattern, str):
        return pattern.translate(_special_chars_map)
    else:
        pattern = str(pattern, 'latin1')
        return pattern.translate(_special_chars_map).encode('latin1')
Run Code Online (Sandbox Code Playgroud)

...虽然它可以将单个字符转换为多个字符(例如[? \[),但不能执行该操作的相反操作。

由于没有直接逆转escape()available via str.translate(),因此如您的问题所述,自定义unescape()函数 usingre.sub()是最直接的解决方案。