mongdb 模糊查询,要检索的内容中还有特殊符号,造成 检索不出来数据,想要实现检测效果,需要对 检测内容中的特殊字符进行转义,才能达到检索效果

一、转义正则特殊字符 方法


    /**
     * 转义正则特殊字符 ($()*+.[]?\^{},|)
     *
     * @param keyword
     * @return
     */
    public static String escapeExprSpecialWord(String keyword) {
        String[] fbsArr = { "\\", "$", "(", ")", "*", "+", ".", "[", "]", "?", "^", "{", "}", "|" };
        for (String key : fbsArr) {
            if (keyword.contains(key)) {
                keyword = keyword.replace(key, "\\" + key);
            }
        }
        return keyword;
    }

二、应用

        Criteria criteria = new Criteria();

        //项目名称
        if (!ObjectUtils.isEmpty(mixingStationProductionRequesJson.getFgcmc())) {
//            criteria.and("fgcmc").regex(".*?" + mixingStationProductionRequesJson.getFgcmc() + ".*?");
            //项目名称中带(),造成检测不出来   将括号用反斜杠"\"进行转义 \(
            String name=escapeExprSpecialWord(mixingStationProductionRequesJson.getFgcmc());
            criteria.and("fgcmc").regex("^.*"+name+".*$");
        }
         Query query = Query.query(criteria);
         List<MixingStationRealDataVo> list=mongoTemplate.find(query,MixingStationRealDataVo.class);
Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐