MongoDB regex, I get a different response from the Java API compared to the console

I must be wrong in my regular expression.

In the console, I do

db.triples.find({sub_uri: /.*pdf.*/ }); and get the desired result.

My Java class is as follows (I set input = "pdf"):

    public static List<Triple> search(String input){

        DB db=null;
        try {
            db = Dao.getDB();
        }
        catch (UnknownHostException e1) {   e1.printStackTrace(); }
        catch (MongoException e1) {         e1.printStackTrace(); }

        String pattern = "/.*"+input+".*/";
System.out.println(input);      

                List<Triple> triples = new ArrayList<Triple>();
                DBCollection triplesColl = null;

                try {
                    triplesColl = db.getCollection("triples");      } catch (MongoException e) { e.printStackTrace();}

                {                   
                    Pattern match = Pattern.compile(pattern, Pattern.CASE_INSENSITIVE);
                    BasicDBObject query = new BasicDBObject("sub_uri", match);

                    // finds all people with "name" matching /joh?n/i
                    DBCursor cursor = triplesColl.find(query);

                    if(cursor.hasNext()){
                    DBObject tripleAsBSON = cursor.next();
                        Triple t = new Triple();
                        t.setSubject(new Resource((String)tripleAsBSON.get("sub_uri")));

System.out.println(t.getSubject().getUri());                

                        triples.add(t);
                    }   
            }
        return triples;
    }

From the console, I get 12 results, as I should, from the Java code, I get no results.

+5
source share
1 answer

Java does not need / understand regex separators ( /around regex). You need to delete them:

String pattern = ".*"+input+".*";

I'm also not sure if this regular expression is really what you want. At least you should bind it:

String pattern = "^.*"+input+".*$";

Pattern.MULTILINE. , input. , input , , ?

+9

All Articles