MongoDB/PyMongo:如何在正则表达式搜索中“转义"参数? [英] MongoDB/PyMongo: how to 'escape' parameters in regex search?
问题描述
我正在使用pymongo,并且想要搜索以某些字符序列开头的项目.我可能会这样实现:
I'm using pymongo and want to do a search for items starting with a certain sequence of characters. I might implement that like this:
items = collection.find({ 'key': '/^text/' })
这应该起作用,但是如果text
是变量怎么办?我可以做类似的事情:
This should work, but what if text
is a variable? I could do something like:
items = collection.find({ 'key': '/^' + variable + '/' })
但是现在,如果variable
中的文本包含具有特殊正则表达式含义的任何字符(例如$
),则查询将不再表现出预期的行为. 是否可以进行某种参数绑定?我必须自己清理variable
吗?这甚至可靠吗?
But now if the text in variable
contains any characters with special regex meaning (such as $
), the query no longer behaves as expected. Is there a way to do some sort of parameter binding? Do I have to sanitize variable
myself? Is that even reliably possible?
谢谢!
推荐答案
您必须以编程方式组装正则表达式.所以:
You have to assemble the regex programmatically. So either:
import re
regex = re.compile('^' + re.escape(variable))
items = collection.find({ 'key': regex })
OR
items = collection.find({'key': { '$regex': '^' + re.escape(variable) }})
请注意,该代码使用 re.escape
对字符串进行转义,以防万一包含特殊字符.
Note that the code uses re.escape
to escape the string in case it contains special characters.
这篇关于MongoDB/PyMongo:如何在正则表达式搜索中“转义"参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!