Chayma Atallah
Chayma Atallah

Reputation: 766

Mongo DB and Java ends with Regex

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.

enter image description here

Upvotes: 1

Views: 1988

Answers (2)

Wiktor Stribiżew
Wiktor Stribiżew

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:

  • You need to match the entire string, so you need to use .* before the expression
  • If a string has newlines, you need to pass the (?s) DOTALL modifier so that . could also match newline symbols
  • You need to Pattern.quote the expression so that it works correctly with queries that have, say, [ in them
  • You do not need ( and ) around expression as this capturing group is not used anywhere later.

Upvotes: 2

Chayma Atallah
Chayma Atallah

Reputation: 766

This is the solution : query.put(pagepath, new BasicDBObject("$regex", ".*(" + expression + ")$"));

Upvotes: -1

Related Questions