我有一个 String
和一个充满搜索项的 String[]
。
如何检查我的 String
是否包含所有搜索项?
这是一个例子:
案例一:
String text = "this is a stupid test";
String[] searchItems = new String[2];
searchItems[0] = "stupid";
searchItems[1] = "test";
案例二:
String text = "this is a stupid test";
String[] searchItems = new String[2];
searchItems[0] = "stupid";
searchItems[1] = "tes";
在情况 1 中,该方法应返回 true
,但在情况 2 中,该方法应返回 false
。
最佳答案
您可以使用 word boundaries 执行此操作在正则表达式中:
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);
}
边界可确保仅当整个单词都出现在您的文本中时才会匹配搜索词。因此,"tes"
将不会与 "test"
匹配,因为 "\btes\b"
不是 "\的子字符串btest\b"
.
关于java - 如何检查字符串是否包含搜索项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25998991/