MongoDB/PyMongo: how to 'escape' parameters in regex search?

▼魔方 西西 提交于 2019-12-18 04:55:22

问题


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/' })

This should work, but what if text is a variable? I could do something like:

items = collection.find({ 'key': '/^' + 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?

Thanks!


回答1:


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) }})

Note that the code uses re.escape to escape the string in case it contains special characters.




回答2:


Here is the concept: you have to use regex

items = collection.find({
     'key' : {
         $regex : yourRegex
     }
})


来源:https://stackoverflow.com/questions/13224753/mongodb-pymongo-how-to-escape-parameters-in-regex-search

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!