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!
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With