MongoDB RegEx not working

淺唱寂寞╮ 提交于 2021-02-05 09:40:45

问题


I'm trying to return documents that whose obsNum field starts with 1.. I have written the following RegEx to filter out those documents however, it returns all the documents that start with 1

Observations.getObservationsModelObject().find({
    "ageGroup": ageGroup,
    "obsNum": {
        $regex: '^\s*1\.'
    }
}, function(err, foundData) {});

What am I doing wrong?

This RegEx '^\s*1\.' is returning the following instead of returning on 1.3, 1.1 & 1.2:

obsNum:  1.3
obsNum:  1.1
obsNum:  1.2
obsNum:  123
obsNum:  121`

回答1:


'^\s*1\.' is a string. The regex after removing backshash escaping will be ^s*1. which means, the string should start with any number of space/s followed by 1 and then any character.

You can use regex literal syntax

$regex: /^\s*1\./

or double-escape backslashes

$regex: '^\\s*1\\.'

I recommend to use literal syntax whenever possible as it is easy and less error-prone.




回答2:


The regular expression you might try is:

^(1\.\d+)

Explanation:

  • ^ Beginning of the string
  • (…) Capturing parentheses: remember the match
  • 1 Literal digit
  • \d decimal digit
  • + At least one


来源:https://stackoverflow.com/questions/43449823/mongodb-regex-not-working

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!