簡體   English   中英

在python中正則表達式和unicode utf-8?

[英]regular expression and unicode utf-8 in python?

我有代碼塊:( 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(高棉解碼高棉符號范圍:19E0-19FF Unicode標准,版本4.0)。我不能。

我的問題 :

如何更改上面的代碼tagname_re = re.compile(r'^[\\w+\\.-]+$', re.UNICODE)以調整我的Unicode字符。因為如果我輸入帶有“នយោបាយ”的標簽我得到了消息?

please use following characters in tags: letters , numbers, and characters \\'.-_\\''

ោ(U + 17C4 KHMER VOWEL SIGN OO)和ា(U + 17B6 KHMER VOWEL SIGN AA)不是字母,它們是組合標記,所以它們不匹配\\ w。

看看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>

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)
នយ

作為另一個小點,在正則表達式中,字符類中的+僅表示字母和標點符號中也允許使用文字+

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM