Python中的正则表达式与Unicode UTF-8?

6 投票
3 回答
8289 浏览
提问于 2025-04-16 14:27

我有一段代码:(Django代码)

        list_temp = []
        tagname_re = re.compile(r'^[\w+\.-]+$', re.UNICODE)
        for key,tag in list.items():
            if len(tag) > settings.FORM_MAX_LENGTH_OF_TAG or len(tag) < settings.FORM_MIN_LENGTH_OF_TAG:
                raise forms.ValidationError(_('please use between %(min)s and %(max)s characters in you tags') % { 'min': settings.FORM_MIN_LENGTH_OF_TAG, 'max': settings.FORM_MAX_LENGTH_OF_TAG})
            if not tagname_re.match(tag):
                raise forms.ValidationError(_('please use following characters in tags: letters , numbers, and characters \'.-_\''))
            # only keep one same tag
            if tag not in list_temp and len(tag.strip()) > 0:
                list_temp.append(tag)

这段代码让我可以使用Unicode字符来设置标签名称。

但是我不明白为什么在使用我的Unicode(高棉文Unicode字符范围:19E0–19FF,Unicode标准第4.0版)时会出现问题。

我的问题是:

我该如何修改上面的代码tagname_re = re.compile(r'^[\w+\.-]+$', re.UNICODE),以适应我的Unicode字符呢?因为如果我输入标签“នយោបាយ”,我就会收到这样的提示:

请在标签中使用以下字符:字母、数字和字符'.-_'

3 个回答

4

看看这个在PyPI上的新正则表达式实现

http://pypi.python.org/pypi/regex

在Python 3中,它显示:

>>> import regex
>>> regex.match("\w", "\u17C4")
<_regex.Match object at 0x00F03988>
>>> regex.match("\w", "\u17B6")
<_regex.Match object at 0x00F03D08>
5

bobince的回答是完全正确的。不过,在你遇到那个问题之前,可能还有另一个问题——tag 确定是 unicode 而不是 str 吗?比如:

>>> str_version = 'នយោបាយ'
>>> type(str_version)
<type 'str'>
>>> print str_version
នយោបាយ
>>> unicode_version = 'នយោបាយ'.decode('utf-8')
>>> type(unicode_version)
<type 'unicode'>
>>> print unicode_version
នយោបាយ
>>> r = re.compile(r'^(\w+)',re.U)
>>> r.search(str_version).group(1)
'\xe1'
>>> print r.search(str_version).group(1)

>>> r.search(unicode_version).group(1)
u'\1793\u1799'
>>> print r.search(unicode_version).group(1)
នយ

还有一个小细节,在你的正则表达式中,字符类里的 + 只是表示在字母和标点的序列中也允许出现一个字面上的 +

6

“ោ”(U+17C4,柬埔寨语的元音符号OO)和“ា”(U+17B6,柬埔寨语的元音符号AA)并不是字母,它们是组合符号,所以在使用 \w 的时候不会被匹配到。

撰写回答