[英]Django __iregex Returns Empty Response
I have an Article
model that takes in articles from users. 我有一个
Article
模型,该模型吸收了用户的文章。 These articles can have #hashtags in them like we have in twitter. 这些文章中可以包含#hashtags ,就像我们在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: 如果我将这些文章保存在“
Article
模型中:
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 我尝试使用Django的
__icontains
过滤器
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. 但是如果用户点击
#exam
,则会返回三篇文章,而不是第一篇。
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. 我可以在'#exam'上添加空间以使其成为'#exam',它可以正常工作,但我希望能够使用正则表达式来实现。
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.
我在后端使用Django 1.6和MySQL。
I suggest you to remove the first \\b
because there isn't a word boudary exists between #
and the space. 我建议您删除第一个
\\b
因为#
和空格之间没有单词boudary存在。 ie, if the value of hash_tag
variable is #exam
, r"\\b{0}\\b"
will produce the regex \\b#exam\\b
. 即,如果
hash_tag
变量的值为#exam
,则r"\\b{0}\\b"
将生成正则表达式\\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. 而且这与
#exam
旁的#exam
不匹配,因为space和#
之间不存在单词边界,所以它将失败。 #
and space are non-word characters. #
和空格是非单词字符。 \\b
matches between a word character and a non-word character. \\b
在单词字符和非单词字符之间匹配。
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! 就是这样!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.