3 回答

TA贡献1848条经验 获得超10个赞
当你写*时,你的意思是像“任何字符串”?
如果是 - 只需使用正则表达式:
for (String blacklist : blackRegex)
{
Pattern p = Pattern.compile(blackRegex);
Matcher matcher = p.matcher(string);
if (matcher.find()
{
return true;
}
}
return false;
blackRegex的一个例子是(someA)(someB).*
使用.*而不是*对于任何字符串,你可以按照java正则表达式指南。

TA贡献1890条经验 获得超9个赞
定义一个黑名单规则类:
class BlackListRule {
private String a;
private String b;
private String c;
BlackListRule(String a, String b, String c) {
this.a = a; this.b = b; this.c = c;
}
public boolean matches(String a, String b, String c) {
return ("*".equals(this.a) || this.a.equals(a))
&&("*".equals(this.b) || this.b.equals(b))
&&("*".equals(this.c) || this.c.equals(c));
}
public int hashCode() {
return Arrays.deepHashCode(new char[][]{a.toCharArray(), b.toCharArray(), c.toCharArray()});
}
public boolean equals(Object o) {
return o instanceof BlackListRule && ((BlackListRule)o).hashCode() == hashCode();
}
}
private Set<BlackListRule> blacklist;
private boolean isBlacklisted(String a, String b, String c) {
return blacklist.stream().anyMatch(rule -> rule.matches(a,b,c));
}
这是一个最小的工作示例,你绝对应该改进它,但你明白了。
你可以在这里试试。

TA贡献1816条经验 获得超4个赞
多亏了您的所有建议,我总结如下(假设黑名单定义来自db):对于每个“abc”黑名单元组,我创建了一个正则表达式模式。然后将这些模式与 OR 连接。|
private void init(SqlRowSet set) {
Set<String> patterns = new HashSet<>();
while (set.next()) {
String a = set.getString(1);
String b = set.getString(2);
String c = set.getString(3);
patterns.add(a + "/" + b + "/" + c);
}
regex = Pattern.compile(String.join("|", patterns));
}
private boolean isBlacklisted(String a, String b, String c) {
return regex.matcher(a+"/"+b+"/"+c).matches();
}
现在,我可以创建我的黑名单,并将其与之匹配。a, b, .*isBlacklisted("a", "b", "anything") = true
添加回答
举报