python - python re (regex) 是否有 unicode 转义序列的替代方案?

标签 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)

但是如果您需要动态构建模式怎么办?

最佳答案

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

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

关于python - python re (regex) 是否有 unicode 转义序列的替代方案?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16541723/

相关文章:

python - 在数据框中查找值介于 x 和 y 之间的单元格

python - 使用 matplotlib 绘制 pandas 数据框时出现 KeyError

python - -> 在 python 函数定义中

regex - 如何在没有灾难性回溯的情况下编写此正则表达式

python - 将 pandas DataFrame 转换为没有额外列的记录数组

javascript - 使用Javascript限制用户上传与格式不匹配的图像名称

ruby - 如何在 Ruby 中查找字符串中特殊字符之间的文本值?

php - PHP preg_replace 中的\w 仅覆盖 UTF-8 字符的第二个字节

c++ - Boost.format 和宽字符

unicode - 如何使Tcl_WriteChars支持Unicode?