1

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

8
  • Try expression + "$". Also, you'd need to escape the . somehow. So, perhaps, BasicDBObject query = new BasicDBObject(); and then query.put(pagepath, Pattern.compile(Pattern.quote(expression)+"$")); Commented Jun 17, 2016 at 10:07
  • tanks but It did not work and I have my query looking like this: { "\"pagepath\"" : { "$regex" : "\\Q.html\\E$"}} Commented Jun 17, 2016 at 10:19
  • Should the column names be inside literal double quotes? Anyway, the regex seems correct now. Commented Jun 17, 2016 at 10:20
  • yep that part is ok (y) Commented Jun 17, 2016 at 10:21
  • That query works in regex101.com but not in Robomongo: Commented Jun 17, 2016 at 10:34

2 Answers 2

2

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.
Sign up to request clarification or add additional context in comments.

Comments

-1

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

1 Comment

Ok, that means you need to match the entire string, matches() in the background. Still, this is not fully correct approach, because you need to quote the expression, else, if it contains special regex metacharacters, you will get an error.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.