Reputation: 766
I am trying to get all documents from my database where the page path ends with a certain expression using this code:
query.put(pagepath, new BasicDBObject(
"$regex", "/(" +expression+ ")$/"));
and where expression is replaced by values like ".html", ".JSON", "contact/", "/"... I get no errors but no results either, even though, when I test my regex on https://regex101.com/ it works and one of the links at least matchs.
Upvotes: 1
Views: 1988
Reputation: 626689
The solution that will account for any special characters in the expression
and potential newline symbols in the string is
query.put(pagepath, new BasicDBObject("$regex", "(?s).*" + Pattern.quote(expression) + "$"));
Four points are:
.*
before the expression
(?s)
DOTALL modifier so that .
could also match newline symbolsPattern.quote
the expression
so that it works correctly with queries that have, say, [
in them(
and )
around expression
as this capturing group is not used anywhere later.Upvotes: 2
Reputation: 766
This is the solution : query.put(pagepath, new BasicDBObject("$regex", ".*(" + expression + ")$"));
Upvotes: -1