Storing regex raw string literal in Django model?

558 views
Skip to first unread message

Victor Hooi

unread,
Oct 13, 2011, 6:58:00 PM10/13/11
to django...@googlegroups.com
Hi,

I have Django model and in one of the fields I need to store a regex string that I can later use.

class Foo(models.Model):
    name = models.CharField(max_length=30, unique=True)
    regex_string = models.TextField()

So for example, the regex_string field might be set to:

r'\d{2}'

I then try to retrieve this later, compile it as a regex expression and use it - however, it doesn't seem to work as planned:

>>> pattern = re.compile(ham.regex_string)
>>> print(pattern.match("22"))
None

Obviously if I pass the raw string literal in directly, it works fine:

>>> pattern = re.compile(r'\d{2}')
>>> pattern.match("22")
<_sre.SRE_Match object at 0x1505100>

If I actually print ham.regex_string, it returns:

u"r'\\d{2}'"

So it's a unicode string, but for some reason the backslashes are doubled-up?

What I actually need is a way to store a regex raw string literal, so that I can retrieve it later and use it in a regex.

Is there a better way of doing this?

Cheers,
Victor

Daniel Roseman

unread,
Oct 14, 2011, 4:42:04 AM10/14/11
to django...@googlegroups.com
So how did you save it in the first place? You don't actually want the `r` and the single quotes, they're just for when you specify the literal in your code. If you did 

    foo.regex_string = r'\d{2}'

it should come out the other side OK. When you print the string in your console, it'll give the doubled-backslash, but that's just the way Python displays them - it would do the same with the original raw string.
--
DR.

 
Reply all
Reply to author
Forward
0 new messages