在查询mongo时用到了正则查询
设字符串为 str = '/ab/cd.ef?g='
直接用正则查询没有匹配。
collection.find({"re":{'$regex':str},'b':{'$nin':[False]}}).count()
原因是 / . ? 都是正则表达式中的特殊字符,如果要保留原义则需要用""来进行转义
即把字符串改成 str = '/ab/cd.ef?g='
但是,由于""在python中是一个特殊符号,所以要用"\"来表示
定义一个把字符转义的函数
def transfer_str(str): new_str = "" special = ['/','^','$','*','+','?','.'] for c in str: if c in special: new_str += '\' new_str += c return new_str
然后调用
collection.find({"re":{'$regex':transfer_str(str)},'b':{'$nin':[False]}}).count()
这样就可以得到正确结果了