Regex \w 似乎忽略了我的 Unicode 字符串。 我创建了以下函数:
extras.py
# -*- coding: utf-8 -*-
def test(word):
print re.sub(r'[^\w]+', '', word, re.U)
从 django shell 中:
import extras
extras.test(u'שלום')
输出是一个空字符串,但在本例中它应该与输入相同。
正则表达式的目的是只保留字母数字字符,但它不起作用。虽然它适用于 ASCII。
可能是什么问题?
请您参考如下方法:
为模式使用原始 unicode 字符串,并确保使用 flags 参数:
# -*- coding: utf-8 -*-
def test(word):
print re.sub(ur'[^\w]+', u'', word, flags=re.U)
然后:
In [9]: test(u'Ã')
Ã
