gpt4 book ai didi

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

转载 作者:IT老高 更新时间:2023-10-28 13:26:44 25 4
gpt4 key购买 nike

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

items = collection.find({ 'key': '/^text/' })

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

items = collection.find({ 'key': '/^' + variable + '/' })

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

谢谢!

最佳答案

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

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

items = collection.find({'key': { '$regex': '^' + re.escape(variable) }})

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

关于regex - MongoDB/PyMongo : how to 'escape' parameters in regex search?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13224753/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com