I want to search values having special characters such as \" $ / . @ > \"
in a document.
Lets consider, I\'ve myKey with values like \"test$aus
Escape all regex special characters:
req.query.name.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
Create a query with regex and option "i" (ignore case):
const databaseQuery.name = new RegExp(`${req.query.name}`, 'i');
Perform a search with a query:
db.collection.find(databaseQuery)
Note: don't forget to create indexes for the fields that you will search through. Indexing fields increases the speed of your regex queries. In my case for my 'name' field it would be like this:
db.collection.createIndex({ name: "text" })
Define the search key under the re.escape
function that will resolve the issue for special character regex.
{search_field: {"$regex": '{}.*'.format(re.escape(search_key)),"$options": 'i'}}
You have to escape $
by \
:
db.myCollection.find({ myKey : /.*\$aus.*/i });
// OR
db.myCollection.find({myKey: { $regex: '.*\\$aus.*', $options: 'i'}})
You can use https://www.npmjs.com/package/regex-escape. It is a good library for escaping special characters to be used in regular expressions
var RegexEscape = require("regex-escape");
let keyword = RegexEscape("{#/}");
// => \{#\/\}
db.myCollection.find({ myKey : { '$regex' : keyword, '$options' : 'mi' });
The Java Equivalent for https://stackoverflow.com/a/52322010/8208083 is as follows:
Pattern p = Pattern.compile("[\\.\\*\\+\\?\\^\\${}\\(\\)|\\]\\[\\\\]");
Matcher m = p.matcher(searchKeyword);
searchKeyword = m.replaceAll("\\\\$0");
This is useful when you need to pass the search keyword in the @Query annotation of Spring.
db.test.insert({word: 'hai('});
db.test.insert({word: 'jana'});
Output be like that :
{ "_id" : ObjectId("56f27fb71d843581261433c6"), "word" : "hai(" }
{ "_id" : ObjectId("56f27ffe1d843581261433c8"), "word" : "jana" }
Note : Want the special char row alone so
db.test.find({word:{$regex:"\\("}});
Output be like this:
{ "_id" : ObjectId("56f27fb71d843581261433c6"), "word" : "hai(" }