python re(regex)是否具有\ u unicode转义序列的替代方法?

时间:2013-05-14 11:14:12

标签: python regex unicode python-unicode unicode-escapes

Python将\ uxxxx视为字符串文字内的unicode字符转义(例如,u“\ u2014”被解释为Unicode字符U + 2014)。但我刚刚发现(Python 2.7)标准正则表达式模块不会将\ uxxxx视为unicode字符。例如:

codepoint = 2014 # Say I got this dynamically from somewhere

test = u"This string ends with \u2014"
pattern = r"\u%s$" % codepoint
assert(pattern[-5:] == "2014$") # Ends with an escape sequence for U+2014
assert(re.search(pattern, test) != None) # Failure -- No match (bad)
assert(re.search(pattern, "u2014")!= None) # Success -- This matches (bad)

显然,如果你能够将你的正则表达式模式指定为字符串文字,那么你可以产生与正则表达式引擎本身理解\ uxxxx转义时相同的效果:

test = u"This string ends with \u2014"
pattern = u"\u2014$"
assert(pattern[:-1] == u"\u2014") # Ends with actual unicode char U+2014
assert(re.search(pattern, test) != None)

但是如果你需要动态构建模式呢?

2 个答案:

答案 0 :(得分:4)

使用unichr() function从代码点创建unicode字符:

pattern = u"%s$" % unichr(codepoint)

答案 1 :(得分:1)

一种可能性是,不是直接调用re方法,而是将它们包含在能够理解它们代表它们的东西中。像这样:

def my_re_search(pattern, s):
    return re.search(unicode_unescape(pattern), s)

def unicode_unescape(s):
        """
        Turn \uxxxx escapes into actual unicode characters
        """
        def unescape_one_match(matchObj):
                escape_seq = matchObj.group(0)
                return escape_seq.decode('unicode_escape')
        return re.sub(r"\\u[0-9a-fA-F]{4}", unescape_one_match, s)

工作示例:

pat  = r"C:\\.*\u20ac" # U+20ac is the euro sign
>>> print pat
C:\\.*\u20ac

path = ur"C:\reports\twenty\u20acplan.txt"
>>> print path
C:\reports\twenty€plan.txt

# Underlying re.search method fails to find a match
>>> re.search(pat, path) != None
False

# Vs this:
>>> my_re_search(pat, path) != None
True

感谢Process escape sequences in a string in Python指出解码(“unicode_escape”)的想法。

但请注意,您不能通过解码(“unicode_escape”)抛出整个模式。它会在某些时候起作用(因为大多数正则表达式的特殊字符在前面放一个反斜杠时不会改变它们的含义),但它一般不起作用。例如,这里使用decode(“unicode_escape”)改变了正则表达式的含义:

pat = r"C:\\.*\u20ac" # U+20ac is the euro sign
>>> print pat
C:\\.*\u20ac # Asks for a literal backslash

pat_revised  = pat.decode("unicode_escape")
>>> print pat_revised
C:\.*€ # Asks for a literal period (without a backslash)