MongoDB正则表达式匹配问题

编程入门 行业动态 更新时间:2024-10-27 14:33:01
本文介绍了MongoDB正则表达式匹配问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

这是我的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正则表达式匹配问题

本文发布于:2023-10-28 00:39:08,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1534989.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:正则表达式   MongoDB

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!