MongoDB正则表达式匹配问题 [英] MongoDB regex matching trouble
问题描述
这是我的MongoDB Shell会话;
Here is my MongoDB shell session;
> db.foo.save({path: 'a:b'})
WriteResult({ "nInserted" : 1 })
> db.foo.findOne()
{ "_id" : ObjectId("58fedc47622e89329d123ee8"), "path" : "a:b" }
> db.foo.save({path: 'a:b:c'})
WriteResult({ "nInserted" : 1 })
> db.foo.find({path: /a:[^:]+/})
{ "_id" : ObjectId("58fedc47622e89329d123ee8"), "path" : "a:b" }
{ "_id" : ObjectId("58fedc57622e89329d123ee9"), "path" : "a:b:c" }
> db.foo.find({path: /a:[a-z]+/})
{ "_id" : ObjectId("58fedc47622e89329d123ee8"), "path" : "a:b" }
{ "_id" : ObjectId("58fedc57622e89329d123ee9"), "path" : "a:b:c" }
很显然,正则表达式/a:[^:]+/
和/a:[a-z]+/
不应与字符串'a:b:c'
匹配,但看起来Mongo在此正则表达式上失败了,有人知道这里发生了什么吗?
Clearly the regex /a:[^:]+/
and /a:[a-z]+/
shouldn't match string 'a:b:c'
, but looks like Mongo failed on this regex, does anyone know what happened here?
它已作为Bug票证提交给MongoDB Jira, MongoDB查询结构中的错误?
It was submitted to MongoDB Jira, as a bug ticket, so is it a bug within MongoDB querying structure?
推荐答案
问题在于部分匹配,因为您没有限制整个单词的正则表达式,所以a:b:c
中存在的部分匹配就是
The trouble is with the partial matching, since you are not restricting the regex for the whole word, the partial match that exists in a:b:c
that is a:b
is resulting in you getting that document.
将下面的正则表达式与^$
一起使用,它们是表示单词开头和结尾的锚点;
Use the following regex with ^$
that are anchors to represent beginning and the end of the word;
db.foo.find({path: /^a:[^:]+$/})
db.foo.find({path: /^a:[a-z]+$/})
这将使正则表达式适用于整个字符串,并忽略上述部分匹配.有关正则表达式锚点的更多信息,请单击此处.
This will make the regex apply for the whole string, and ignore the partial matches as explained above. For more on regex anchors, click here.
因此,总而言之,没有错误,只是正则表达式的误用.
这篇关于MongoDB正则表达式匹配问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!