NirMH
NirMH

Reputation: 4949

How to filter for "." in MongoDb regex filter?

I am trying to run a query against a mongodb database. The user query is a regular expression in a format similar to perl. I'm translating the user's regex to Mongo filter.

Here is the query code:

private List<string> GetDocuments(string by_regex)
{
    string regex = by_regex.Replace("[", @"\[");
    regex = regex.Replace("]", @"\]");
    regex = regex.Replace("*", ".*");
    regex = "^" + regex + "$";

    var filter = string.Format("{{_id:'CRF^{0}'}}", regex);
    MyObject item = collection.Find(filter).SingleOrDefault(); 
    ....
}

Invoking the above method with the regular expression *.crc is throwing an exception at the Find statement:

Invalid escape sequence in JSON string '\.'.

The filter at runtime is {_id:'CRF^^.*\\.crc$'} - so I assume this is something with the . char escaping, but for some reason I can't find the right way to escape it for Mongo to not complaint.

Upvotes: 1

Views: 1503

Answers (2)

Julio
Julio

Reputation: 5308

According to the error message, MongoDB seems to try to decode JSON string like \., and that is not a valid scape sequence.

See: https://www.freeformatter.com/json-escape.html

So perhaps you shoud change . to \\\\. so that will be encoded as a real \\ that will be decoded in JSON as \

Alternativelly, as I said in my comment, sometimes It is way much easier to use classes for scaping characters. So you may use the [.]. That way you avoid the use of backslashes, which are special characters too and they may need to be scaped several times depending of whether the regular expression is a string or not.

Upvotes: 1

Andrew Komiagin
Andrew Komiagin

Reputation: 6566

You have to escape dot in your regexp like this:

db.Test.find({filename: { $regex: '.*\\.crc', $options: 'i'}})

Upvotes: 1

Related Questions