0

I am working with MongoDB and I am searching the documents with regex expression as below.

new BsonDocument("$regex", "^(?i)" + PropertyValue + "$")

If we exactly know where the special character comes we can add '\' before it. But this value is dynamic here.

One way I can see is I can replace all these special characters with appending '\' before the special characters. But I need to look at what are the special characters on the web and also check if there is any special cases this will fail.

Is there any elegant way of doing this using regex expression.

trincot
  • 317,000
  • 35
  • 244
  • 286
Nithin B
  • 601
  • 1
  • 9
  • 26
  • 1
    If that is JavaScript, then check [this](https://stackoverflow.com/questions/3561493/is-there-a-regexp-escape-function-in-javascript) – trincot Feb 02 '20 at 20:13
  • @trincot Thanks for the suggestion. I am using c# and looking for a similar function. I know this works, but I am looking if the regex itself has some way to do this. – Nithin B Feb 02 '20 at 20:18
  • .NET regex does not support `\Q` and `\E` operators, so use `Regex.Escape` – Wiktor Stribiżew Feb 02 '20 at 20:20
  • @WiktorStribiżew Thanks for the solution. But I would like to say that I google for a solution and didn't find the link you gave probably because of the question. It doesn't exactly describe the problem(All special characters at once). – Nithin B Feb 02 '20 at 20:28

0 Answers0