问题 Java Mongodb正则表达式查询


我必须用Java运行这个查询

 db.Users.find({"name": /^ind/i})

我的Java代码是

Document findQuery = new Document();
findQuery.append("name", Pattern.compile("/^"+name+"/i"));
FindIterable<Document> iterable = db.getCollection("Users").find(findQuery);

它没有返回任何数据,我认为上面的java代码正在转换

> /^ind/i into "/^ind/i"

提前致谢。

编辑:

基于stribizhev建议更新查询及其工作

db.Users.find({"name": {"$regex": /^ind/, "$options": "i"}})

Java代码

Document regQuery = new Document();
regQuery.append("$regex", "^(?)" + Pattern.quote(name));
regQuery.append("$options", "i");

Document findQuery = new Document();
findQuery.append("name", regQuery);
FindIterable<Document> iterable = db.getCollection("Users").find(findQuery);

7027
2017-09-22 10:18


起源

在Java中,不要使用正则表达式分隔符。尝试 "^(?i)"+Pattern.quote(name) 代替 "/^"+name+"/i"。 - Wiktor Stribiżew
谢谢,它的工作原理基本上是“^(?)”+ Pattern.quote(“ind”)将值转换为^(?)\ Qind \ E - Indrajeet
是的,这是事实。我发布了这个建议作为答案。 - Wiktor Stribiżew
请指定您使用的导入。 import java.util.regex.Pattern; - Marco Fantasia


答案:


您不能在Java中使用正则表达式分隔符 Pattern.compile,因为Java中有其他方法(例如标志)也可以这样做。

要强制执行不区分大小写的搜索,请使用内联修饰符 (?i)。所以, 使用 "^(?i)"+Pattern.quote(name) 代替 "/^"+name+"/i"

Pattern.quote 只是逃避所有正则表达式元字符,以便将它们视为文字(与...相同) \Q...\E)。


5
2017-09-22 10:33



是的,所以我更新了mongo查询以及使用这个db.Users.find({“name”:{“$ regex”:/ ^ ind /,“$ options”:“i”}})Java代码是文件regQuery = new Document(); regQuery.append(“$ regex”,“^(?)”+ Pattern.quote(name)); regQuery.append(“$ options”,“i”); - Indrajeet
最后,您可以将此代码添加到问题中。 - Wiktor Stribiżew


我想通过使用MongoDB Java驱动程序(版本3及更高版本)中提供的过滤器,在Java中有更优雅的方法:

Document query = new Document("equipment","gloves");

//whatever pattern you need. But you do not need the "/" delimiters
String pattern = ".*" + query.getString("equipment") + ".*";

//find(regex("field name", "pattern", "options"));
collection.find(regex("equipment", pattern, "i"));

3
2017-10-06 13:03





你可以使用Pattern -and Filters-

Pattern regex = Pattern.compile("ind", Pattern.CASE_INSENSITIVE);
Bson filter = Filters.eq("name", regex);

对象Pattern有一些其他标志,就像你可以看到的那样 这里


1
2018-06-23 21:30





这里的大部分答案对我不起作用(也许不是最新的MongoDB Java驱动程序)。这对我有用:

Document regexQuery = new Document();
regexQuery.append("$regex", ".*" + Pattern.quote(searchTerm) + ".*");
BasicDBObject criteria = new BasicDBObject("name", regexQuery);
DBCursor cursor = collection.find(criteria);

0
2017-08-14 14:04