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.