在ObjectBox中,在String属性下搜索完整单词的简单方法是什么?

问题描述

我有一个名为“ sentence”的属性,它是一个字符串。假设我想查找所有包含“ in”作为单词的句子(而不是任何字符串)。有什么简单的方法? “包含”似乎不接受“ \ bin \ b”之类的正则表达式?

解决方法

我建议使用两级方法:

  1. 使用“包含”查询条件来减少不使用正则表达式的候选人的数量
  2. 在正则表达式上应用query filter以获得实际结果

在代码中,它应该看起来像这样:

Pattern pattern = Pattern.compile(myRegexPattern);
// Reduce object count to reasonable value.
box.query().contains(MyType_.myText,"in")
        // Filter is performed on candidate objects.
        .filter((obj) -> pattern.matcher(obj.myText).matches());

第1步主要是将结果集从所有对象简化为候选对象。在数据库端可以更有效地完成此操作。

,

就API而言,一种简单的方法是使用String.matches(),传入一个正则表达式以匹配整个字符串:

if (str.matches(".*?\\bin\\b.*")) {
    ....
}

否则,您可以使用Pattern和Matcher类进行“完整”的正则表达式匹配。本质上,编译一个Pattern对象,从该对象创建一个Matcher到您的字符串中,然后除了matchs()之外,还为您提供了find()方法。例如:

    Pattern p = Pattern.compile("\\bin\\b");
    if (p.matcher(str).find()) {

    }

后者更加灵活,因为您可以更轻松地执行诸如设置匹配器选项(例如区分大小写)之类的操作,或者查询匹配项的实际位置。

,
import re

s = """
The dishes go in the dishwasher. 
Please put the plates in the sink.
The dishes are in your room
hahahaha
in room
..... in
inin
you wont find the word you are looking for"""

pattern = re.compile(".*\\bin\\b.*",flags=re.M)

print(pattern.findall(s))

# ("\w.*\\bin\\b.*",flags=re.M)

1)。* =选择任何单词,字符,数字等。

2) \ b =单词边界,这意味着您要从头开始锁定单词的首字母,因此此处的句子='this inis the',仅使用\ bin也会匹配句子“ this inis the”,因为您仅从起点而不是终点标出边界。 \ b [word] \ b将根据您的情况做

3)标志= re.M使我们可以分别考虑每行。否则,匹配项将位于整个字符串“ s”上,而不是每一行上

4) findall找到匹配项