【问题标题】:Django regex unicode ignores \w tagDjango 正则表达式 unicode 忽略 \w 标记
【发布时间】:2012-07-29 15:54:55
【问题描述】:

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。

可能是什么问题?

【问题讨论】:

    标签: python regex django unicode


    【解决方案1】:

    对模式使用原始 unicode 字符串,并确保使用 flags 参数:

    # -*- coding: utf-8 -*-
    def test(word):
        print re.sub(ur'[^\w]+', u'', word, flags=re.U)
    

    然后:

    In [9]: test(u'Ã')
    Ã
    

    【讨论】:

    • 我不敢相信这是失踪的flags=。感谢您的回答!
    • 只注意flags in .sub() 仅在 python 2.7 中添加!
    猜你喜欢
    • 2012-03-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-21
    • 2015-10-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多