简体   繁体   English

在Django的Charfield上使用正则表达式

[英]Using regex on Charfield in Django

I have a model with 我有一个模特

class dbf_att(models.Model):
    name = models.CharField(max_length=50, null=True)

And i'd like to check later that object.name match some regex: 而且我想稍后再检查object.name是否与某些正则表达式匹配:

    if re.compile('^\d+$').match(att.name):
        ret = 'Integer'
    elif re.compile('^\d+\.\d+$').match(att.name):
        ret = 'Float'
    else:
        ret = 'String'
  return ret

This always return 'String' when some of the att.name should match those regex. 当某些att.name应该与那些正则表达式匹配时,总是返回“ String”。

Thanks! 谢谢!

You can try with RegexValidator 您可以尝试使用RegexValidator

Or you can to it with package django-regex-field , but i would rather recommand you to use built-in solution, the less third-party-apps the better. 或者,您也可以使用django-regex-field软件包来实现 ,但是我宁愿建议您使用内置解决方案,第三方应用越少越好。

Regex are great, but sometimes it is more simpler and readable to use other approaches. 正则表达式很棒,但是有时使用其他方法更简单易读。 For example, How about just using builtin types to check for the type 例如,如何仅使用内置类型检查类型

try:
    att_name = float(att.name)
    ret = "Integer" if att_name.is_integer() else "Float"
except ValueError:
    ret = "String"

FYI, your regex code works perfectly fine. 仅供参考,您的正则表达式代码运行正常。 You might want to inspect the data that is being checked. 您可能要检查正在检查的数据。

Demo: 演示:

>>> import re
>>> a = re.compile('^\d+$')
>>> b = re.compile('^\d+\.\d+$')
>>> a.match('10')
<_sre.SRE_Match object at 0x10fe7eb28>
>>> a.match('10.94')
>>> b.match('10')
>>> b.match('10.94')
<_sre.SRE_Match object at 0x10fe7eb90>
>>> a.match("string")
>>> b.match("string")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM