这里有一些代码使用正则表达式来快速内部循环如果无的测试字符串在目标字符串中找到。
public static void main(String[] args) throws Exception {
List<String> haystack = Arrays.asList(new String[] { "ABCD", "EFGH", "IJ KL", "M NOP", "UVW X" });
List<String> needles = Arrays.asList(new String[] { "IJ", "NOP" });
// To cut down on iterations, create one big regex to check the whole haystack
StringBuilder sb = new StringBuilder();
sb.append(".*(");
for (String needle : needles) {
sb.append(needle).append('|');
}
sb.replace(sb.length() - 1, sb.length(), ").*");
String regex = sb.toString();
for (String target : haystack) {
if (!target.matches(regex)) {
System.out.println("Skipping " + target);
continue;
}
for (String needle : needles) {
if (target.contains(needle)) {
System.out.println(target + " contains " + needle);
}
}
}
}
输出:
Skipping ABCD
Skipping EFGH
IJ KL contains IJ
M NOP contains NOP
Skipping UVW X
如果你真的想要得到可爱的,你可以平分使用二进制搜索,以确定该目标列表的匹配段,但它可能不值得。
这取决于它是多么可能yo'll发现一个打击。低命中率会带来好的结果。高命中率的表现并不比简单的嵌套循环版本更好。如果一些针头击中多个目标,则考虑倒置环路,其他击中任何一个。
这是所有关于尽快中止搜索路径。
* “我能得到'list.contains的情况下,'真'(” IJ “)'?” *发生了什么事,当你试过* *呢? –
返回'false' – y2p
你必须知道*它匹配的是哪一个确切的*项,还是足以知道它与你的一个术语相匹配(不知道哪一个)? – Bohemian