【发布时间】:2016-11-25 03:11:48
【问题描述】:
我需要基于 unicode 字符串构建一个 re 模式(例如,我有“word”,我需要类似 ^"word"| "word" 的东西)。但是,“单词”可以包含特殊的 re 字符。要按原样匹配“单词”,我需要转义 unicode 字符串中的特殊 re 字符。基本的 re.escape() 函数可以处理 ascii 字符串。我怎样才能为 unicode 做到这一点?
【问题讨论】:
-
你能给minimal reproducible example,而不是描述吗?
-
re.escape()确实适用于 Unicode 字符串。你能举一个没有给出正确结果的例子吗? -
在 python 2.7 中,转义函数是这样实现的:` _alphanum = freezeset( "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789") def escape(pattern): "Escape all non-alphanumeric characters in pattern." s = list(pattern) alphanum = _alphanum for i, c in enumerate(pattern): if c not in alphanum: if c == "\000": s[i] = "\\000" else: s[i] = "\\" + c 返回模式[:0].join(s) `
-
好的,我同意它插入了许多不必要的反斜杠。但它们也不会损害正则表达式的正确性,是吗?
-
谢谢,re.escape() 确实有效,我没有意识到这一点。我只是忘记了“|”后面的括号。
标签: python regex unicode escaping