@Test
public void name() {
// drop everything
mongoTemplate.dropCollection(Promotion.class);
// persist entity with value field equls to "Rate $"
final Promotion promotion = new Promotion();
promotion.setValue("Rate $");
mongoTemplate.insert(promotion);
// persist entity with value field equls to "Rate %"
final Promotion promotion2 = new Promotion();
promotion2.setValue("Rate %");
mongoTemplate.insert(promotion2);
// RETURNS EMPTY COLLECTION
Query query = new Query();
query.addCriteria(Criteria.where("value").regex("Rate $", "i"));
List<Promotion> promotions = mongoTemplate.find(query, Promotion.class);
assertThat(promotions.size(), is(0));
// query with escaped $
// FINDS THE RECORD SUCCESSFULLY
Query query2 = new Query();
query2.addCriteria(Criteria.where("value").regex("Rate \\$", "i"));
promotions = mongoTemplate.find(query2, Promotion.class);
assertThat(promotions.size(), is(1));
assertThat(promotions.get(0).getValue(), is("Rate $"));
}
2条答案
按热度按时间mbyulnm01#
您正在提供正则表达式模式(
promotionInput.getDealType()
在本例中)而不转义特殊正则表达式字符。特殊正则表达式元字符:
., +, *, ?, ^, $, (, ), [, ], {, }, |, \.
在你的情况下,promotionInput.getDealType()
包含未转义的美元符号,在提供正则表达式搜索之前应该转义。如果美元符号($)位于整个正则表达式的末尾,则它与行的末尾匹配。
如果整个正则表达式由插入符号和美元符号(^如$)括起来,则它与整行匹配。
mongodb中的数据
测试:用regex搜索值
测试已成功执行且呈绿色。
9njqaruj2#
if(promotioninput.getdealtype()!=(空){
query.addcriteria(criteria.where(promotionmasterconstants.deal类型\u db).regex(promotioninput.getdealtype().replace(“$”,“$”,“i”));}
这得花点时间$