On Thursday, 13 October 2011 23:58:00 UTC+1, Victor Hooi wrote: > > 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 >
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. -- You received this message because you are subscribed to the Google Groups "Django users" group. To view this discussion on the web visit https://groups.google.com/d/msg/django-users/-/qMNLMe601Y0J. To post to this group, send email to django-users@googlegroups.com. To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com. For more options, visit this group at http://groups.google.com/group/django-users?hl=en.