【问题标题】:How to validate unicode "word characters" in Python regex?如何在 Python 正则表达式中验证 unicode “单词字符”?
【发布时间】:2012-09-22 00:16:23
【问题描述】:

我有带字段的表单:

name = forms.RegexField(regex=r'\w+$', label=u'Name', required=True)

但如果我输入特殊字符(例如ś)表单,则不会通过 is_valid() 函数。怎么做?

【问题讨论】:

    标签: python regex django django-forms


    【解决方案1】:

    \w激活Unicode matching

    name = forms.RegexField(regex=r'(?u)\w+$', label=u'Name', required=True)
    

    【讨论】:

      【解决方案2】:

      除了将正则表达式定义为字符串,您可以先将其编译为正则表达式对象,设置re.U 标志:

      import re
      
      name_regex = re.compile(r'\w+$', re.U)
      name = forms.RegexField(regex=name_regex, label=u'Name', required=True)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-08-04
        • 1970-01-01
        • 1970-01-01
        • 2021-12-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-07-11
        相关资源
        最近更新 更多