0

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`
3
  • 1
    You're passing the regex as String so, backslashes need to be double-escaped. Use $regex: /^\s*1\./ Commented Apr 17, 2017 at 10:50
  • @Tushar You are absolutly correct. That's was the only problem with my regex. Can you please tell me why do we need to put double backslash in a regex string? Commented Apr 17, 2017 at 10:52
  • Because in string, backslash is used to escape following character. Thus, one for escaping and other is for metacharacters in regex. Or simply use regex literal syntax as shown in first comment. Commented Apr 17, 2017 at 10:54

2 Answers 2

2

'^\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.

Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.