英文:
Having an issue with my regex query to Mongo in Java
问题
String searchQuery = "st";
BsonDocument regexFilter = Filters.regex("name", "^.*" + Pattern.quote(searchQuery), "i").toBsonDocument(null, null);
userQuery.putAll(regexFilter);
FindIterable<Document> allDocs = mongoCollection.find(userQuery);
上述是我目前执行查询时运行的代码。
如果我在mongo的name
字段中寻找子字符串"st",我仍然会找到name
字段甚至不包含子字符串"st"的值。
然而,每当我将模式从:
"^.*" + Pattern.quote(searchQuery)
更改为
"^" + Pattern.quote(searchQuery)
我会获得正确的结果,但只有当name
字段中的字符串以"st"开头时,比如"Stephanie"。这不是我想要的...我也应该能够获得像"Justin"这样的名字。目前,使用顶部的示例代码,我还会得到"Nalissa",它甚至不包含"st"...
英文:
String searchQuery = "st";
BsonDocument regexFilter = Filters.regex("name", "^.*" + Pattern.quote(searchQuery), "i").toBsonDocument(null, null);
userQuery.putAll(regexFilter);
FindIterable<Document> allDocs = mongoCollection.find(userQuery);
The above is all I run currently when doing a query.
If I am looking for a substring "st" in the name
field in mongo, I will still be finding values where the name
field doesn't even contain the substring "st".
However, whenever I change the pattern from:
"^.*" + Pattern.quote(searchQuery)
to
"^" + Pattern.quote(searchQuery)
I will get correct results, but only if the String in the name field starts with "st", like "Stephanie". Which isn't what I want...I should also be getting names like "Justin". Currently I am getting "Nalissa" with the sample code at the very top as well which doesn't even contain st...
答案1
得分: 1
在Java领域,与许多其他语言不同的是,只有当正则表达式完全与“String”匹配时,才认为匹配成功。
在你的正则表达式末尾添加“.*”:
BsonDocument regexFilter = Filters
.regex("name", ".*" + Pattern.quote(searchQuery) + ".*", "i")
.toBsonDocument(null, null);
还要注意,你不需要在开头加“^”或者在结尾加“$”,因为当必须匹配整个“String”时,它们是隐含的。
英文:
In Java land, unlike many other languages, a String
matches a regex if, and only if, the entire String
is matched by the regex.
Add ".*"
to the end of your regex:
BsonDocument regexFilter = Filters
.regex("name", ".*" + Pattern.quote(searchQuery) + ".*", "i")
.toBsonDocument(null, null);
Note also that you don't need "^"
at the start or "$"
at the end, because they are implied when having to match the entire String
.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论