mongo模糊查询,带有特殊字符需要转义,再去查询
mongo模糊查询,带有特殊字符需要转义,再去查询
·
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);
更多推荐



所有评论(0)