Matching the whole word only in a Django request

I am trying to write a Django request that will match whole words. Based on the answer here , I tried something like:

result = Model.objects.filter(text__iregex='\bsomeWord\b') 

But this does not return the expected result. I also tried

 result = Model.objects.filter(text__iregex=r'\bsomeWord\b') 

to no avail. My ultimate goal is to be able to pass a string variable, for example:

 result = Model.objects.filter(text__iregex=r'\b'+stringVariable+r'\b') 

or

 result = Model.objects.filter(text__iregex=r'\b %s \b'%stringVariable) 

But now I can’t even get it to work with a raw string. I am using PostgreSQL.

+11
django regex postgresql django-queryset
source share
3 answers

Use ' \ y ' instead of ' \ b ' when you use PostgreSQL, this is because Django passes your regular expression directly to PostgreSQL - so your RegEx should be compatible with this. You should be able to execute them from psql without any problems.

 result = Model.objects.filter(text__iregex=r"\y{0}\y".format(stringVariable)) 

See https://www.postgresql.org/docs/9.1/functions-matching.html#POSIX-CONSTRAINT-ESCAPES-TABLE

+18
source share

You might be able to get something by dropping the regex and using multiple django searches

 result = Model.objects.filter(Q(text__contains=' someword ') | Q(text__contains=' someword.') | Q(text__istartswith = 'someword.' | Q(text__istartswith = 'someword.' | Q(text__iendswith = 'someword') 

see here for the docs.

I understand that it’s not very elegant (but it simplifies maintenance if you are not a fan of regular expression).

+1
source share

I had the same problem trying to match word boundaries using the Perl compatible escape sequence \ b. My database is MySQL.

I solved the problem with the expression of the character class [[: space:]], for example.

  q_sum = Q() search_list = self.form.cleaned_data['search_all'].split(' '); for search_item in search_list: search_regex = r"[[:space:]]%s[[:space:]]" % search_item q_sum |= Q(message__iregex=search_regex) queryset = BlogMessages.objects.filter(q_sum).distinct() 
0
source share

All Articles