在Java中使用正则表达式与集合的代码部分不要翻译。

huangapple go评论86阅读模式
英文:

Using regex with sets in Java

问题

我有一个在Java中的集合其中包含不同的字符串比如'+Cat','+Dog'等等我还有一个如下所示的字符串

    animals = '+Cat|+Dog|+Goat';

基本上如果集合包含了animals中列出的任何动物我想要返回false我应该如何实现这个我不确定是否可以在contains方法中使用正则表达式而且我字符串中的'+'符号会让正则表达式更复杂
英文:

I have a set in Java with different strings, such as '+Cat', '+Dog', etc. I also have a string as shown below.

animals = '+Cat|+Dog|+Goat'

Basically, if the set contains any of the animals listed in animals, I want to return false. How would I go about doing this? I am not sure if you can use regex with contains. Furthermore the fact that I have the + in my string complicates regex.

答案1

得分: 6

public boolean containCheck(Set<String> newset) {
    String animals = "+猫|+狗|+山羊";
    for (String op : animals.split("\\|")) {
        if (newset.contains(op)) {
            return false;
        }
    }
    return true;
}
英文:
public boolean containCheck(Set&lt;String&gt; newset) {
    String animals = &quot;+Cat|+Dog|+Goat&quot;;
    for (String op : animals.split(&quot;\\|&quot;)) {
        if (newset.contains(op)) {
            return false;
        }
    }
    return true;
}

答案2

得分: 1

可以将字符串拆分为数组,并使用for循环检查集合中是否包含数组中的任何元素。

public Boolean isContaining(String animals, Set<String> sets ) {
    for (String s : animals.split("\\|")) {
        for (String set : sets) {
            if (s.equals(set)) {
                return false;
            }
        }
    }
    return true;
}
英文:

You can split the string in array and use a for loop to check it the set contains any element presents in the array.

public Boolean isContaining(String animals, Set&lt;String&gt; sets ) {
	for (String s : animals.split(&quot;\\|&quot;)) {
		for (String set : sets) {
			if (s.equals(set)) {
				return false;
			}
		}
	}
	return true;
}

huangapple
  • 本文由 发表于 2020年4月7日 17:25:22
  • 转载请务必保留本文链接:https://go.coder-hub.com/61076765.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定