bobby
bobby

Reputation: 183

Mongodb driver regex find

    String pattern = ".*" + "a? I'm" + ".*";
    FindIterable<Document> document = collection.find(regex("mypost", pattern, "i")).sort(new Document("mypost", -1));

I want a regex that contains the terms "a? I'm". For some reason this pattern picks up collections with mypost as "? I'm" when I want only "a? I'm".

What is wrong with it?

Upvotes: 0

Views: 44

Answers (1)

Ivan Vasiljevic
Ivan Vasiljevic

Reputation: 5708

The problem with your regex is that ? has special meaning

? - Once or none

So your regex is basically saying - before " I'm" you can have a or not.

Your regex in fact should look like this:

String pattern = ".*" + "a\\? I'm" + ".*";

By adding \\ you should specify that you want to use ? as a character.

Upvotes: 1

Related Questions