Python MongoDB 正则表达式:忽略大小写

17 投票
4 回答
11970 浏览
提问于 2025-04-16 11:41

我该如何指定一个正则表达式,并且忽略大小写呢:

regex = ".*" + filter + ".*";
config.gThingCollection.find({"name":{"$regex":regex}})

我想让这个过滤器不区分大小写,应该怎么做呢?

4 个回答

4
res = posts.find({"geography": {"$regex": 'europe', "$options": 'i'}})

# if you need use $not
import re
res = posts.find(
    {"geography": {"$not": re.compile('europe'), "$options": 'i'}})

当然可以!请把你想要翻译的内容发给我,我会帮你用简单易懂的语言解释清楚。

26

你可以在查询中使用MongoDB的正则表达式选项,像这样:

config.gThingCollection.find({"name":{"$regex":regex, "$options": "i"}})
33

试着使用Python的正则表达式对象。Pymongo会正确地处理它们:

import re
config.gThingCollection.find({"name": re.compile(regex, re.IGNORECASE)})

撰写回答