MongoDB/PyMongo:如何在正则表达式搜索中"转义"参数?

Sam*_*Sam 6 regex mongodb pymongo

我正在使用pymongo并且想要搜索以特定字符序列开头的项目.我可能会这样实现:

items = collection.find({ 'key': '/^text/' })
Run Code Online (Sandbox Code Playgroud)

这应该有效,但如果text是变量呢?我可以这样做:

items = collection.find({ 'key': '/^' + variable + '/' })
Run Code Online (Sandbox Code Playgroud)

但是现在如果文本variable包含任何具有特殊正则表达式含义的字符(例如$),则查询不再按预期运行.有没有办法做某种参数绑定?我必须自己消毒variable吗?这甚至可靠吗?

谢谢!

Joh*_*yHK 9

您必须以编程方式组装正则表达式.所以要么:

import re
regex = re.compile('^' + re.escape(variable))
items = collection.find({ 'key': regex })
Run Code Online (Sandbox Code Playgroud)

要么

items = collection.find({'key': { '$regex': '^' + re.escape(variable) }})
Run Code Online (Sandbox Code Playgroud)

请注意,代码用于re.escape转义字符串,以防它包含特殊字符.