how to check whether a string contains any element specified in a set of elements? say for eg: how to check whether below statement 'I got two dogs and a cat'
contains words specified in set {dog,cat,parrot}
Salesforce Stack Exchange is a question and answer site for Salesforce administrators, implementation experts, developers and anybody in-between. It only takes a minute to sign up.
Sign up to join this communityhow to check whether a string contains any element specified in a set of elements? say for eg: how to check whether below statement 'I got two dogs and a cat'
contains words specified in set {dog,cat,parrot}
You can use the Pattern
and Matcher
class, constructing the regexp pattern from the values of the set, or you could loop through each value in the set and compare it to a value. Solutions are ordered from most flexible to least flexible.
Pattern p = Pattern.compile(String.join(new List<String>(keyWords),'|'));
Matcher m = p.matcher(targetString);
if(m.find()) { ... }
Boolean matches = false;
for(String key:keyWords) {
if(targetString.indexOf(key)>-1) {
matches = true;
break;
}
}
set
has not a method called containsAny
, but a string
. And containsAny
checks for any character and not for the word.
– Sergej Utko
Aug 29 '13 at 20:17
String test='There are two dogs and a cat';
set<string> a=new Set<string>{'dog','cat','pat'};
boolean check=false;
List<String> lsttest=test.split(' ');
for(String s: lsttest){
if(a.contains(s)){
check=true;
break;
}
}
system.debug('check...'+check);
You can use the above also to find whether string contains any word
The following code works pretty well without any loop :
Set<String> keyWords = new Set<String>{'dog','cat','pat'};
if(JSON.serialize(keyWords).contains('dog'))
{
System.debug('It contains dog!');
}
contains
, as it is a Set
instance method. Besides, this doesn't answer OP's question, as you are comparing to a single string only, whereas he wants to find words of that string in the set.
– André Medeiros
Aug 29 '13 at 22:43