Reputation: 419
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:
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.
Thanks!
Upvotes: 0
Views: 952
Reputation: 99630
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")
Upvotes: 0
Reputation: 106
You can try with 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.
Upvotes: 1