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}


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 and Matcher

Pattern p = Pattern.compile(String.join(new List<String>(keyWords),'|'));
Matcher m = p.matcher(targetString);
if(m.find()) { ... }
  • Can be modified to match whole words only, can be made case insensitive, and isn't affected by punctuation.

Search and Compare

Boolean matches = false;
for(String key:keyWords) {
    if(targetString.indexOf(key)>-1) {
        matches = true;
  • Matches any part of any word; matching whole words would be rather difficult without a complex condition statement.
  • I think a 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
  • You can not use String.join with a Set sorry ^^ – Cloud Ninja Aug 29 '13 at 22:31
  • Thanks for reminding me of that. You can, however, convert a set to a string on the fly, so I've updated the answer to reflect this. – sfdcfox Aug 30 '13 at 12:38
  • Solution with Pattern/matcher won´t work if for example a keyword contains round brackets. Invalid regex error – Enry Jul 28 '18 at 9:22
 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){


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'};
    System.debug('It contains dog!');
  • 1
    It is completely unnecessary to serialize the set before calling 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
  • Oh yeah my bad sorry – Cloud Ninja Aug 29 '13 at 22:46

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.