MongoDB 正则表达式,与控制台相比,我从 Java API 得到了不同的答案
我的正则表达式一定是错误的。
在控制台中,我执行
db.triples.find({sub_uri: /.*pdf.*/ }); 并获得所需的结果。
我的 Java 类看起来像这样,(我设置了 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;
}
从控制台我得到了 12 个结果,这是我应该得到的,从 Java 代码我没有得到任何结果。
I must be doing my regex wrong.
In the console I do
db.triples.find({sub_uri: /.*pdf.*/ });
and get the desired result.
My Java class looks like this, (I have 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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
Java 不需要/理解正则表达式分隔符(正则表达式周围的
/
)。您需要删除它们:我也不确定该正则表达式是否真的是您想要的。至少您应该锚定它:
并使用
Pattern.MULTILINE
选项编译它。如果某行不包含子正则表达式输入
,这可以避免严重的性能损失。您知道input
是一个正则表达式,而不是逐字字符串,对吧?Java doesn't need/understand regex delimiters (
/
around the regex). You need to remove them:I'm also not sure if that regex is really what you want. At least you should anchor it:
and compile it using the
Pattern.MULTILINE
option. This avoids a severe performance penalty if a line doesn't contain your sub-regexinput
. You are aware thatinput
is a regex, not a verbatim string, right?