Ram*_*ses 1 java regex string search-engine contains
我有一个String和一个String[]充满搜索项目.
如何检查我是否String包含所有搜索项?
这是一个例子:
情况1:
String text = "this is a stupid test";
String[] searchItems = new String[2];
searchItems[0] = "stupid";
searchItems[1] = "test";
Run Code Online (Sandbox Code Playgroud)
案例2:
String text = "this is a stupid test";
String[] searchItems = new String[2];
searchItems[0] = "stupid";
searchItems[1] = "tes";
Run Code Online (Sandbox Code Playgroud)
在情况1中,该方法应该返回true,但在情况2中该方法应该返回false.
您可以使用正则表达式中的单词边界来执行此操作:
boolean result = true;
for (String item : searchItems) {
String pattern = ".*\\b" + item + "\\b.*";
// by using the &&, result will be true only if text matches all patterns.
result = result && text.matches(pattern);
}
Run Code Online (Sandbox Code Playgroud)
边界确保只有在文本中出现整个单词时才匹配搜索项.所以,"tes"不会匹配"test"因为"\btes\b"不是子串"\btest\b".