简体   繁体   中英

Django __iregex Returns Empty Response

I have an Article model that takes in articles from users. These articles can have #hashtags in them like we have in twitter. I have these hashtags converted to links that users can click to load all articles that have the clicked hashtags in them.

If I have these articles saved in Article model:

1.  'For the love of learning: why do we give #Exam?'
2.  'Articles containing #Examination should not come up when exam is clicked'
3.  'This is just an #example post'

I tried using Django's __icontains filter

def hash_tags(request, hash_tag):
    hash_tag = '#' + hash_tag
    articles = Articles.objects.filter(content__icontains=hash_tag)
    articles = list(articles)
    return HttpResponse(articles)

but if user clicks on #exam the three articles are returned instead of the first one.

I can add space to '#exam' to become '#exam ' and it will work out fine but I want to be able to do it with regex.

I have tried:

articles = Articles.objects.filter(content__iregex=r"\b{0}\b".format(hash_tag))

but I get empty response.

How do I do this correctly to have it work? I am using Django 1.6 and MySQL at backend.

I suggest you to remove the first \\b because there isn't a word boudary exists between # and the space. ie, if the value of hash_tag variable is #exam , r"\\b{0}\\b" will produce the regex \\b#exam\\b . And this won't match #exam present next to the space, since there isn't a word boundary exists between space and # , so it would fail. # and space are non-word characters. \\b matches between a word character and a non-word character.

content__iregex=r"{0}\b".format(hash_tag)

Add a case-insensitive modifier if necessary.

content__iregex=r"(?i){0}\b".format(hash_tag)

I was able to do this finally.

articles = Articles.objects.filter(content__iregex=r"^[^.]*{0}*[[:>:]]".format(hash_tag))

And that's it!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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