【问题标题】:Regex for the django form fielddjango 表单字段的正则表达式
【发布时间】:2012-03-22 17:06:00
【问题描述】:

我有一个表单域:

web_address = forms.RegexField(regex=r'^DO SOMETHING$', error_messages = {'invalid': _("Not a valid web address.")})

我无法为上述地址编写正则表达式。我的要求是以http://maps.google.com/maps/place?cid=1234 的形式验证网址。 id 1234 是一个变体,但先验是不变的。

请帮忙!!!

【问题讨论】:

    标签: python regex django django-forms


    【解决方案1】:

    只有两件事要知道

    1. ?. 是正则表达式中的特殊字符,需要转义
    2. 检查数字,要么使用预定义的类\d,要么定义你自己的[0-9]并至少说一个\d+

    所以你的正则表达式应该看起来像

    ^http://maps\.google\.com/maps/place\?cid=\d+$
    

    如果您想了解更多关于正则表达式的信息,www.regular-expressions.info 是一个不错的起点。

    要测试您的正则表达式,您可以使用在线测试器,例如gskinner.com/RegExr/。你可以看到你的正则表达式here

    【讨论】:

      【解决方案2】:

      这应该可行:

      web_address = forms.RegexField(regex=r'^http\\:\\/\\/maps\\.google\\.com\\/maps\\/place\\?cid\\=\d+'$', error_messages = {'invalid': _("Not a valid web address.")})
      

      IE:

      >>> import re
      >>> re.match('^http\\:\\/\\/maps\\.google\\.com\\/maps\\/place\\?cid\\=\d+',      'http://maps.google.com/maps/place?cid=1234', re.IGNORECASE)
      <_sre.SRE_Match object at 0x1251fa8>
      

      【讨论】:

        猜你喜欢
        • 2016-06-01
        • 1970-01-01
        • 2015-07-04
        • 2014-01-29
        • 2019-03-08
        • 2013-06-09
        • 1970-01-01
        • 2012-10-21
        • 1970-01-01
        相关资源
        最近更新 更多