1

I am trying to create JSON query string for MongoDB, In order to support regular expression I need to create JSON string that has values without quotes. How do accomplish this in java,

Here is the example of what I am trying to do,

  JSONObject obj= new JSONObject();
  String title = "gro";
  obj.put("title", "/.*" + title + ".*/");

Result is

   {"title ":"/.*gro.*/"}

Above is no longer treated as a regular expression by MongoDB. What i wanted is,

   {"title ":/.*gro.*/}

So that MongoDB treats it as a regular expression. Is there any way to accomplish this in java?

2
  • 1
    {"title ":/.*gro.*/} is not valid JSON, so I doubt you'll find any JSON parser/marshaller that will generate that. Commented Mar 8, 2013 at 15:27
  • This would result in invalid JSON. What library are you using and what do you want to accomplish? [For what do you need the regular expression?] Commented Mar 8, 2013 at 15:27

2 Answers 2

1

The / delimited regular expression syntax is a JavaScript construct. In Java you have to use java.util.regex.Pattern like this:

BasicDBObject query = new BasicDBObject("title", Pattern.compile(".*gro.*"));
Sign up to request clarification or add additional context in comments.

Comments

0

Try this,

  JSONObject obj= new JSONObject();
  String title = "gro";
  String startExpr = "/.*";
  String endExpr = ".*/";

  obj.put("title", startExpr  + title + endExpr );

Comments

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.