Mongo $ regex,带括号和单词边界 [英] Mongo $regex with Parenthesis and Word Boundary

查看:88
本文介绍了Mongo $ regex,带括号和单词边界的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

提供以下文档

{
  "_id": "test-id",
  "text": "this is some text and (0aef4666-3627-4c24-8e50-b0cf9a723823)"
}

以下mongo查询返回文档:

The following mongo query returns the document:

{"text":{"$regex":"\\(0aef4666-3627-4c24-8e50-b0cf9a723823\\)","$options":"iu"}}

但是这个没有:

{"text":{"$regex":"\\b\\(0aef4666-3627-4c24-8e50-b0cf9a723823\\)\\b","$options":"iu"}}

我想在单词边界上搜索uid.我以为添加\ b可以正确地将其拾取,但即使我要查找的术语位于文本的中间,它也显然不匹配(我认为也许它在字符串末尾的事实正在影响它,但似乎不是).

I want to search for the uid on the word boundary. I thought adding \b would properly pick it up, but it apparently does not match, even if the term I'm looking for is in the middle of the text (I thought perhaps the fact it was at the end of the string was affecting it, but it doesn't appear to be).

为什么这不起作用,如何使括号内的词与整个词"匹配?

Why doesn't this work and how can I get my parenthetical term to match on the "whole word"?

推荐答案

这是因为\b仅在其两边都有文字字符时才匹配.在您的情况下,\b用空格字符和开/闭括号括起来,这两个都不是单词"字符.因此,\b匹配失败.

It's because \b only matches if there's a word character on either side of it. In your case, the \b is surround by a space character and a open/close parenthesis, neither of which are a "word" character. Therefore the \b match fails.

你可以做

\\b0aef4666-3627-4c24-8e50-b0cf9a723823\\b

,它将与\b匹配,因为现在它位于单词边界上.

which will match the \b because now it is on a word boundary.

或者,您也可以匹配空格或行首/行尾:

Alternatively, you could match against a space OR start/end-of-line:

db.test.find({"text": /(^|\s)\(0aef4666-3627-4c24-8e50-b0cf9a723823\)($|\s)/i} )

这篇关于Mongo $ regex,带括号和单词边界的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆