【问题标题】:Django __iregex Returns Empty ResponseDjango __iregex 返回空响应
【发布时间】:2015-02-19 08:50:26
【问题描述】:

我有一个Article 模型,它接收来自用户的文章。这些文章中可以包含 #hashtags,就像我们在 twitter 中一样。我将这些标签转换为链接,用户可以点击这些链接来加载所有包含点击标签的文章。

如果我将这些文章保存在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'

我尝试使用 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)

但如果用户点击#exam,则返回三篇文章而不是第一篇。

我可以在 '#exam' 中添加空间以成为 '#exam',它会正常工作,但我希望能够使用正则表达式来做到这一点。

我试过了:

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

但我得到的回复是空的。

如何正确执行此操作才能使其正常工作?我在后端使用 Django 1.6 和 MySQL。

【问题讨论】:

    标签: python mysql regex django


    【解决方案1】:

    我建议您删除第一个\b,因为# 和空格之间不存在单词边界。即,如果hash_tag 变量的值为#examr"\b{0}\b" 将产生正则表达式\b#exam\b。这与空格旁边的#exam 不匹配,因为空格和# 之间不存在单词边界,所以它会失败。 # 和空格是非单词字符。 \b 匹配单词字符和非单词字符。

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

    如有必要,添加不区分大小写的修饰符。

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

    【讨论】:

    • 我刚刚尝试过,但它从后端返回此错误OperationalError at /mysite/get_hashtags/Exam/ (1139, "Erreur 'repetition-operator operand invalid' provenant de regexp")
    • 你试过这个content__iregex=r"{0}\b".format(hash_tag) 吗?
    • 我刚做了。 content__iregex=r"{0}\b".format(hash_tag) 返回空响应,content__iregex=r"(?i){0}\b".format(hash_tag) 返回我报告的错误。
    • hash_tag 变量的值是多少?
    • regex101.com/r/bO4zV5/3 它在这里工作。但不要为什么它不匹配。
    【解决方案2】:

    我终于能够做到这一点。

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

    就是这样!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-01-18
      • 2023-03-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多