8

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}

3 Answers 3

11

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;
        break;
    }
}
  • Matches any part of any word; matching whole words would be rather difficult without a complex condition statement.
4
  • I think a set has not a method called containsAny, but a string. And containsAny checks for any character and not for the word. Commented Aug 29, 2013 at 20:17
  • You can not use String.join with a Set sorry ^^
    – brovasi
    Commented Aug 29, 2013 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
    Commented Aug 30, 2013 at 12:38
  • Solution with Pattern/matcher won´t work if for example a keyword contains round brackets. Invalid regex error
    – Enry
    Commented Jul 28, 2018 at 9:22
7
 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

0

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!');
}
2
  • 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. Commented Aug 29, 2013 at 22:43
  • Oh yeah my bad sorry
    – brovasi
    Commented Aug 29, 2013 at 22:46

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .