在Java中对Mongo的正则表达式查询遇到问题。

huangapple go评论67阅读模式
英文:

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 = &quot;st&quot;;
BsonDocument regexFilter = Filters.regex(&quot;name&quot;, &quot;^.*&quot; + Pattern.quote(searchQuery), &quot;i&quot;).toBsonDocument(null, null);

userQuery.putAll(regexFilter);

FindIterable&lt;Document&gt; 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:

&quot;^.*&quot; + Pattern.quote(searchQuery)

to

&quot;^&quot; + 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 &quot;.*&quot; to the end of your regex:

BsonDocument regexFilter = Filters
  .regex(&quot;name&quot;, &quot;.*&quot; + Pattern.quote(searchQuery) + &quot;.*&quot;, &quot;i&quot;)
  .toBsonDocument(null, null);

Note also that you don't need &quot;^&quot; at the start or &quot;$&quot; at the end, because they are implied when having to match the entire String.

huangapple
  • 本文由 发表于 2020年10月1日 07:56:21
  • 转载请务必保留本文链接:https://go.coder-hub.com/64147317.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定