2012-10-10 133 views
2

PCRE正则表达式我有一个unicode字符串unicode字符串在Python

 u"\uC3A9\xe9"
,我要转换的PCRE在Python支持正则表达式
"\x{c3a9}\x{e9}"

是否有任何模块已经这样做?

回答

2

我不知道任何模块要做到这一点,但这里是一个潜在的解决方案:

import re 

def pcre_escape_repl(match): 
    char = match.group(0) 
    if ord(char) in range(32, 127): 
     # if this is a printable ascii character, use re.escape instead of a \x escape 
     return re.escape(char) 
    # replace non-ascii (or non-printable) characters with a \x escape 
    return r'\x{' + hex(ord(char))[2:] + '}' 

def pcre_escape(s): 
    regex = re.compile('.', re.DOTALL) 
    return regex.sub(pcre_escape_repl, s) 

例子:

>>> print pcre_escape(u"\uC3A9\xe9") 
\x{c3a9}\x{e9} 
>>> print pcre_escape("[foo]{bar}") 
\[foo\]\{bar\} 
+0

感谢@ F.J这是有帮助的。 –